Page 1 of 1

simple number validation

Posted: Thu Dec 24, 2009 10:28 am
by dimxasnewfrozen
I'm trying to validate if a variable is a number or not

I'm using the is_numeric() function but it sees a set of numbers a string for example..
12345567

Is there another function I can use to check if the variable is a number?

Re: simple number validation

Posted: Thu Dec 24, 2009 10:36 am
by AbraCadaver

Code: Select all

$string = '12345567';
$number = 12345567;
 
if(is_numeric($string)) {
    echo "THIS IS A NUMBER\n";
}
 
if(is_numeric($number)) {
    echo "THIS IS A NUMBER\n";
}
Output is:

THIS IS A NUMBER
THIS IS A NUMBER

What is the problem?

Re: simple number validation

Posted: Thu Dec 24, 2009 10:47 am
by MichaelR

Code: Select all

 
 
$string = '12345';
$number =  12345;
 
if (is_int($string) || is_float($string)) {
  echo '$string is a number.' . PHP_EOL;
}
 
if (is_int($number) || is_float($number)) {
  echo '$number is a number.' . PHP_EOL;
}
 
// Outputs: $number is a number.
 

Re: simple number validation

Posted: Thu Dec 24, 2009 7:03 pm
by requinix
You mean whether the variable is actually a number type?

Code: Select all

if (is_int($number) || is_double($number))
Since PHP is loosely-typed I tend to stay away from those.