Reputation: 107
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.
Upvotes: 2
Views: 4757
Reputation: 16253
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
Upvotes: 0
Reputation: 9351
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.
Upvotes: 4
Reputation: 1268
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
?>
Upvotes: 3