PHP: check variable type 

Joined:
03/10/2011
Posts:
84

April 29, 2011 13:43:13    Last update: April 29, 2011 13:44:34
List of functions testing variable type:

FunctionDescription
is_boolFinds out whether a variable is a boolean
is_doubleAlias of is_float()
is_floatFinds whether the type of a variable is float
is_intFind whether the type of a variable is integer
is_integerAlias of is_int()
is_longAlias of is_int()
is_nullFinds whether a variable is NULL
is_numericFinds whether a variable is a number or a numeric string
is_objectFinds whether a variable is an object
is_realAlias of is_float()
is_scalarFinds whether a variable is a scalar
is_stringFind 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
Share |
| Comment  | Tags