PHP Data Types


PHP supports eight primitive types.

Four scalar types:

  1. string
  2. integer
  3. float
  4. boolean

Two composite types:

  1. array
  2. object

Two special types:

  1. resource
  2. NULL

View variable type

Through the gettype() function can easily see the type of a variable:

$var_bool = TRUE; // a boolean
$var_str = " foo " // a string
$var_int = 12; // an integer

echo gettype($var_bool); // Output boolean
echo gettype($var_str); // Output string
echo gettype($var_int); // Output integer

Tips

  1. For historical reasons, if the data type float, gettype() function returns a double, not float.
  2. if you want to see the value and type of an expression, use the var_dump() function.

Determine the variable type

if you want to determine the next logical action by determining the type of the variable, do not use gettype(), but instead use the is_type family of functions:

$var_int = 12;

// if $var_int is of type int, this is added
if(is_int($var_int)) {
    $var_int = $var_int + 4;
}
echo $var_int; // output 16



Copyright 2014-2017 by DeveloperTut.com. All Rights Reserved.
TwitterGoogle+Facebook