Question

I wrote the following php code,

<?php
 $k ="123e5";
if(is_numeric($k)){
    echo "is number";
}
else{
    echo "is not a number";
}
?>

the expected out put is "is not a number" because e is present in the string. But I got the output "is number". why is that happens? and please help me to find the solution.

Was it helpful?

Solution 2

You can use ctype_digit() to check for numeric character(s)

http://www.php.net/manual/en/function.ctype-digit.php

<?php

$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>

OTHER TIPS

as per doc of is_numeric:

Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.

so it is given right output.

I think you are looking for integer only. use is_int() then.

You should use PHP's built in filter functions to validate user input. Please have a look at the following handbook pages: http://www.php.net/manual/en/book.filter.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top