Is it numeric value?


I have 3 variables like the above.

myVariable1 is numeric.
myVariable2 is half numeric.
myVariable3 is not numeric.

I like to check each variable of myVariables is numeric or not numeric.

The code below doesn’t work correctly, but I hope it shows what I want.

if ( $myVariable is numeric )

echo 'Yes, it's numeric';
echo 'No, it's not numeric';

Have a look at PHP: is_int - Manual

Possibly is_numeric() instead of is_int(): PHP: is_numeric - Manual

is_int() only checks for integers. is_numeric() checks for ints, decimals/floats, and exponential value notation.

Like Force Flow said. is_numeric() is boolean, so it returns true if numeric and false if not numeric.

if ( is_numeric($myVariable) )

echo "Yes, it's numeric";
echo "No, it's not numeric";

Building on Mikes’ hint that you look at using (int) to typecast to an integer, look at these examples:

$myVar[0]=12;  // an int
$myVar[1]='1a'; // a string starting with an int
$myVar[2]='ab'; // a string with no ints
$myVar[3]='12'; // a string containing ints
$myVar[4]='a1'; // a string containing an int but starting with a non-int
$myVar[5]='1.8'; // a string containing a float

foreach( $myVar as $v)
echo (int)$v . '<br>';
// gives
1  // nb does not round up

Depending on what you want to do with the likes of “1a”, where PHP tries to analyse it as a number, finds a 1, thats OK, then finds an a, so drops it.

Whereas if the string starts with a non-numeric char “a1” it gives up and returns 0.

typical use:

if( (int)$var === 0) {
// failed the int test - send away
// passed the int test - get on processing

I use this a lot when I am expecting, say, a numerical id key to be passed from a form element. Short and sweet, and therefore memorable ;).

So you have got to be very clear in your mind what you want to happen in your middle test “1a”