PHP Data Types
PHP supports the following primitive data types:
- bool: a value that’s either
trueorfalse. - int: a whole number value.
- float: a numeric value with decimal.
- string: a series of characters.
- array: an ordered map of key/value pairs.
- object: an instance of a pre-defined class.
- callable: a reference to a PHP function.
- iterable: represents any array or object implementing the
Traversableinterface. - resource: a reference to an external resource.
- NULL: represents a variable with no value.
Rather than being declared in code, the data type is decided at runtime depending on the context. There are many ways to determine the type of a variable or expression.
Printing the Type and Value
The var_dump() function prints out the type and value of an expression.
Example
$text = "PHP";var_dump($text);
The output looks like this:
string(3) "PHP"
The gettype() Function
The gettype() function returns a human readable string representing the data type of an expression.
Example
$text = "PHP";echo(gettype($text));
Results in the output:
string
Checking Types
PHP has a number of “is_type” functions to check the type of a variable.
is_bool($value)returnstrueif$valueis a bool value.is_int($value)returnstrueif$valueis an int value. (Alsois_integer().)is_float($value)returnstrueif$valueis a float value.is_string($value)returnstrueif$valueis a string.is_array($value)returnstrueif$valueis an array value.is_object($value)returnstrueif$valueis an object value.is_iterable($value)returnstrueif$valueis an iterable value.is_resource($value)returnstrueif$valueis a resource value.is_null($value)returnstrueif$valueis aNULLvalue.
The is_callable() function has a slightly more complicated syntax:
is_callable($value, $syntax_only, $callable_name)
Where $value is the value being checked. The $syntax_only parameter is an optional boolean flag that if set true will only check if $value is properly structured to be used as a callback. The $callable_name parameter is optional, and if included, will be set to the name of the callable function or method referred to by $value. The function will return true if $value is a callable value.
Codebyte Example
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours