Examining Variable Type and Content

Because PHP is flexible with types, it provides the following functions that can check a variable's type:

boolean is_int(mixed variable)
boolean is_float(mixed variable)
boolean is_bool(mixed variable)
boolean is_string(mixed variable)
boolean is_array(mixed variable)
boolean is_object(mixed variable)

All the functions return a Boolean value of true or false for the variable variable, depending on whether it matches the variable type that forms the name of the function. For example, the following prints 1, that is, true:

$test = 13.0;
echo is_float($test); // prints 1 for true Debugging with print_r( ) and var_dump( )

PHP provides the print_r( ) and var_dump( ) functions, which print the type and value of an expression in a human-readable form:

print_r(mixed expression)
var_dump(mixed expression [, mixed expression ...])

These functions are useful for debugging a script, especially when dealing with arrays or objects. To test the value and type of $variable at some point in the script, the following code can be used:

$variable = 15;

This prints:


While the var_dump( ) function allows multiple variables to be tested in one call, and provides information about the size of the variable contents, print_r( ) provides a more concise representation of arrays and objects. These functions can be used on variables of any type, and we use them throughout this chapter to help illustrate the results of our examples.

by BrainBellupdated