2.1 Checking Whether a Variable Is a Valid Number


You want to see whether a variable is a number.

Technique

Use the is_int() function along with the is_float() function:

 <?php if (is_int ($var)  is_float ($var)) {     // .. $var is a number } ?> 

Comments

The is_int() and is_float() functions take a variable and return true if the variable is the correct type (type integer for is_int ; type float for is_float ).

PHP 4 has a convenient function, is_numeric() , that enables you to check whether the variable passed to it is a number or a numeric string, such as "34" or "-12.3" .

 <?php $num1 = '23.32'; if (is_float ($num1)  is_int ($num1)) {     print '$num1 is a number'; } elseif (is_numeric ($num1)) {     print '$num1 may not be a number, but its contents are numeric'; } else {     print '$num1 is neither a number or numeric'; } ?> 

Finally, you can check whether your variable is a number by getting its type with the gettype() function:

 <?php if ((gettype ($var) == "integer")  (gettype ($var) == "float")) {     // .. It is a number } ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net