PHP Variable Validation

Judge a variable’s type

To get the type of a variable, use gettype() function.

It returns the type as string. Returned values are:

  • “boolean”
  • “integer”
  • “double” (for historical reasons “double” is returned in case of a float, and not simply “float”)
  • “string”
  • “array”
  • “object”
  • “resource”
  • “resource (closed)” as of PHP 7.2.0
  • “NULL”
  • “unknown type”

Examples

$t = gettype( True ); // "boolean"
$t = gettype( 1 );    // "integer"
$t = gettype( 1.1 );  // "double"
$t = gettype( NAN );  // "double"
$t = gettype( 'a' );  // "string"
$t = gettype( [1] );  // "array"
$t = gettype( $foo ); // "NULL", notice will ge given because $foo is not defined.
$t = gettype( new stdClass );   // "object"

There are a series of is_* functions that can be used to determine whether a variable is a certain kind of “type”. These functions accept an variable and return a boolean to indicate the is_* checking is true or false.

PHP’s ten primitive types (including one pseudo-type iterable) checking.

Other “type” checking.

  • is_scalar(), find whether a variable is a scalar. Only types boolean, integer, float, string are scalar.
  • is_numeric(), find whether a variable is a number or a numeric string.
  • is_countable(), verify that the contents of a variable is an array or an object implementing Countable.
  • is_finite(), check whether a float value is a legal finite number on this platform. It accepts a float parameter.
  • is_infinite(), check whether a float value is infinite on this platform. It returns TRUE if a variable is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform.

These are alias of existing is_* functions.

  • is_integer(), alias of is_int().
  • is_long(), alias of is_int().
  • is_double(), alias of is_float().
  • is_real(), alias of is_float().

Examples

// is_numeric()
$r = is_numeric( '12' );   // true
$r = is_numeric( '09' );   // true
$r = is_numeric( "10e0" ); // true
$r = is_numeric( "0x41" ); // false

// is_iterable()
$r = is_iterable( [1, 2, 3] );                       // true
$r = is_iterable( new ArrayIterator( [1, 2, 3] ) );  // true
$r = is_iterable( ( function (){ yield 1; } ) () );  // true
$r = is_iterable( new stdClass() );                  // false

// is_countable()
$r = is_countable( [1, 2, 3] );                 // true
$r = is_countable( ArrayIterator(['a', 'b' ) ); // true
$r = is_countable( new ArrayIterator() );       // true
$r = is_countable( new stdClass() );            // false

// is_finite(), is_infinite()
$r = is_finite( 1.0 / 3); // true
$f = acos( 2 );
$r = is_finite( $f );     // false
$r = is_infinite( $f );   // false
$r = is_nan( $f );        // true

// is_callable()

// prototype: is_callable ( mixed $var [, bool $syntax_only = FALSE [, string &$callable_name ]] ) : bool

function foo() {}
$r = is_callable( 'foo' );    // true

$func = function () {};
$r = is_callable( $func );    // true

class Foo {
    public function __construct() {}
    public function foo() {}
}

$obj = new Foo();
$class_func = array( $obj, 'foo' );
$r = is_callable( $class_func );                   // true

// Note in PHP 5.3.0 is_callable() reports constructors as not being callable. 
$r = is_callable( array( 'Foo', '__construct' ) ); // false
$r = is_callable( array( 'Foo', 'foo' ) );         // false

// The second parameter $syntax_only is false by default.
// If it is set to ture, it only reject simple variables that are not strings, 
// or an array that does not have a valid structure to be used as a callback. 
$r = is_callable( array( 'Foo', '__construct' ), true );   // true
$r = is_callable( array( 'Foo', 'foo' ), true );           // true

Valid a variable’a value

Before use a variable, it is a good idea to check whether it is properly initialized. is_set() and empty() will help you.

  • isset(), determine whether a variable is declared and is different than NULL.
  • empty(), determine whether a variable is empty. A variable is considered empty:
    • it does not exist.
    • its value equals FALSE. A variable is considered FALSE:
    • boolean FALSE
    • integer 0 and -0
    • float 0.0 and -0.0
    • empty string
    • empty array
    • NULL
    • object SimpleXML created from empty tags

You may notice that is_null() may help as well. But note that if it takes an undefined parameter, you will have notice information,the other two functions will not bring notice. Therefor use isset() first to make sure a variable has been set a value then check the type using is_*() functions.

  • is_null(), determine whether a variable is NULL. A variable is considered to be NULL:
    • it has been assigned the constant NULL.
    • it has not been set to any value yet.
    • it has been unset with function unset().

Relationships between isset(), empty() and is_null(): a variable is true either in isset() or is_null(). empty() contains is_null and part of isset().

// --------isset()

$a = 1;
$b = 'hello';
var_dump( isset( $a ) ); // bool(true)

// isset() can take more than one parameters. 
// It returns TRUE only if all of the parameters are considered set. 
var_dump( isset( $a, $b, $c ) ); // bool(false)
var_dump( isset( $c ) );         // bool(false)

// --------empty()

empty( $c ); // bool(true)

// --------is_null()

var_dump( is_null( $c ) ); // bool(false), but it will give notice for $f is undefined.

Test/Debug a variable’s type and value

To test or debug a variable’s type and value, you may use var_dump() function. This function displays structured information about one or more expressions that includes its type and value.

$a = 1.1;
var_dump( $a );
/* output: 
float(3.1)
*/

$b = true;
var_dump( $a, $b ); // display morn than one expressions
/* output:
float(1.1)
bool(true)
*/

$c = array (
    1,
    'a' => 'Apple',
    'color' => array ( 'Red', 'Green', 'Blue' )
);
var_dump( $c );
/* ouput:
array(3) {
  [0]=>
  int(1)
  ["a"]=>
  array(1) {
    [0]=>
    string(5) "Apple"
  }
  ["color"]=>
  array(3) {
    [0]=>
    string(3) "Red"
    [1]=>
    string(5) "Green"
    [2]=>
    string(4) "Blue"
  }
}
*/

In addition to var_dump(), you can also use print_r() and var_export(). Compared to var_dump():

  • print_r() outputs or returns value about a variable in a way that’s readable by humans.
  • var_export() outputs or returns a parsable string representation of a variable. The returned representation is a valid PHP code.
// print_r prototype:
// print_r( mixed $expression [, bool $return = FALSE ] ) : mixed

print_r( $c );
/* output:
Array
(
    [0] => 1
    [a] => Array
        (
            [0] => apple
        )

    [color] => Array
        (
            [0] => Red
            [1] => Green
            [2] => Blue
        )

)
*/

print_r( $c, true ); // It will return the information rather than output it.

// var_export prototype:
// var_export ( mixed $expression [, bool $return = FALSE ] ) : mixed

var_export( $c );
/* output:
array (
  0 => 1,
  'a' =>
  array (
    0 => 'apple',
  ),
  'color' =>
  array (
    0 => 'Red',
    1 => 'Green',
    2 => 'Blue',
  ),
)
*/

$v = var_export( $c, true ); 
    // It will return the variable representation rather than output it.
    // Now $v is a valid piece of code which represted in string as showed above.
eval( '$d' . $v . ';' );
var_dump( $d );
/* output:
array(3) {
  [0]=>
  int(1)
  ["a"]=>
  array(1) {
    [0]=>
    string(5) "apple"
  }
  ["color"]=>
  array(3) {
    [0]=>
    string(3) "Red"
    [1]=>
    string(5) "Green"
    [2]=>
    string(4) "Blue"
  }
}
*/