How to Check Data Type in PHP: Simple Guide
gettype() function, which returns the type as a string. Alternatively, use specific is_int(), is_string(), is_array(), and similar functions to check if a variable is of a certain type.Syntax
The main function to check a variable's data type is gettype($variable), which returns the type as a string like "integer", "string", or "array".
For checking specific types, PHP provides functions like is_int($variable), is_string($variable), is_array($variable), etc., which return true if the variable matches the type, otherwise false.
<?php // Check type with gettype $type = gettype($variable); // Check if variable is integer if (is_int($variable)) { // do something } ?>
Example
This example shows how to use gettype() to print the type of different variables and how to use is_string() and is_array() to check specific types.
<?php $var1 = 123; $var2 = "hello"; $var3 = [1, 2, 3]; // Using gettype() echo "Type of var1: " . gettype($var1) . "\n"; echo "Type of var2: " . gettype($var2) . "\n"; echo "Type of var3: " . gettype($var3) . "\n"; // Using is_* functions if (is_string($var2)) { echo "var2 is a string\n"; } if (is_array($var3)) { echo "var3 is an array\n"; } ?>
Common Pitfalls
One common mistake is confusing gettype() output with boolean checks. gettype() returns a string describing the type, not a boolean.
Also, using loose comparisons (==) instead of strict checks can cause unexpected results when checking types.
For example, is_int('123') returns false because '123' is a string, even if it looks like a number.
<?php $var = '123'; // Wrong: expecting true but returns false var_dump(is_int($var)); // bool(false) // Right: convert string to int first var_dump(is_int((int)$var)); // bool(true) ?>
Quick Reference
| Function | Description |
|---|---|
| gettype($var) | Returns the type of $var as a string |
| is_int($var) | Checks if $var is an integer |
| is_string($var) | Checks if $var is a string |
| is_array($var) | Checks if $var is an array |
| is_bool($var) | Checks if $var is a boolean |
| is_float($var) | Checks if $var is a float (double) |