Everything PHP: Checking Types

Published on May 13, 2009   //  Development
Off

Everything PHP

Previously, we covered the different types of data that exist in PHP. Generally, you’ll be able to tell what type you’re dealing with, just by looking at it. However, what about dynamic data? Data that you didn’t type out in your code could be any number of different types.

That’s where a series of type-checking functions in PHP come into play. These functions all work the same, in that you pass the data to it (usually in the form of a variable), and it will return either true if the data is that type, and false otherwise. These functions are named in the format of is_*().

PHP, contains one of these functions for each of the possible types. The functions are is_array(), is_bool(), is_float(), is_int(), is_null(), is_numeric(), is_object(), is_resource() and is_string().

While you’ll still have to use some logic in which types you should be testing for (for instance, you’ll never get a resource from a submitted form), these functions do provide some assurance in the type of data you’ll dealing with. Some of these functions are a bit tricky on what data is true or not, but these examples should clear that up:

[code='php']var_dump(is_int(2)); // bool(true)
var_dump(is_int('2')); // bool(false)
var_dump(is_int(2.5)); // bool(false)
var_dump(is_int('2.5')); // bool(false)

var_dump(is_numeric(2)); // bool(true)
var_dump(is_numeric('2')); // bool(true)
var_dump(is_numeric(2.5)); // bool(true)
var_dump(is_numeric('2.5')); // bool(true)
var_dump(is_numeric('foo')); // bool(false)

$foo = NULL;
$bar = '';
var_dump(is_null($foo)); // bool(true)
var_dump(is_null($bar)); // bool(false)
var_dump(is_null($nonexistent)); // bool(true)[/code]

If you have no idea what type of data you’re dealing with, you can use the gettype() function. However, it is slow and recommend you avoid it where possible.