How to Check a Variable Contain a Valid Number?

How to Expose and Route to a Resource?
How to Expose and Route to a Resource?

Problem:- How to Check a Variable Contain a Valid Number?,
You want to ensure that a variable contains a number,
even if it’s typed as a string.
Alternatively, You want to check if a variable is not only a number,
but is also specifically typed as one.

Solution – Check a variable Contains a Valid Number or Not?

<?php
foreach([5, '10', 20, 'five', 30, '10e200', 0xDECAFBAD] as $check_no){
	$isNumeric = is_numeric($check_no);
	$variable_type = gettype($check_no);
	print 'Is the '. $variable_type.' '.$check_no.' numeric?';
	if($isNumeric){
		print 'Yes';
	}else{
		print 'No';
	}
	print "\n";
}
?>

How it Works?

1st of all we put mixed number and string in a array. then we use foreach loop to convert in a single variable on by one in $check_no. After that we use is_numeric() function that return true or false when a single variable entered. then we use gettype() function to know the type of the $check_no variable. After that we use condition to print yes or not as based on condition.

इसे भी पढ़े – How to Trim Blanks from a String Using PHP?

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *