PHP: check variable type
April 29, 2011 13:43:13 Last update: April 29, 2011 13:44:34
List of functions testing variable type:
Test code:
Output:
| Function | Description |
|---|---|
| is_bool | Finds out whether a variable is a boolean |
| is_double | Alias of is_float() |
| is_float | Finds whether the type of a variable is float |
| is_int | Find whether the type of a variable is integer |
| is_integer | Alias of is_int() |
| is_long | Alias of is_int() |
| is_null | Finds whether a variable is NULL |
| is_numeric | Finds whether a variable is a number or a numeric string |
| is_object | Finds whether a variable is an object |
| is_real | Alias of is_float() |
| is_scalar | Finds whether a variable is a scalar |
| is_string | Find whether the type of a variable is string |
Test code:
<?php class A { } $a = array(1, 1.2, '1', 'a', true, new A(), null); $func = array ( 'is_bool', 'is_double', 'is_float', 'is_int', 'is_integer', 'is_long', 'is_null', 'is_numeric', 'is_object', 'is_real', 'is_scalar', 'is_string', ); foreach ($a as $i) { echo 'var_dump: ', var_dump($i); echo "-------------------------\n"; foreach ($func as $f) { if ($f($i)) { echo "$f: true\n"; } } echo "\n"; } ?>
Output:
var_dump: int(1)
-------------------------
is_int: true
is_integer: true
is_long: true
is_numeric: true
is_scalar: true
var_dump: float(1.2)
-------------------------
is_double: true
is_float: true
is_numeric: true
is_real: true
is_scalar: true
var_dump: string(1) "1"
-------------------------
is_numeric: true
is_scalar: true
is_string: true
var_dump: string(1) "a"
-------------------------
is_scalar: true
is_string: true
var_dump: bool(true)
-------------------------
is_bool: true
is_scalar: true
var_dump: object(A)#1 (0) {
}
-------------------------
is_object: true
var_dump: NULL
-------------------------
is_null: true