Current Location: Home> Latest Articles> PHP Function to Get Variable Data Type with Examples

PHP Function to Get Variable Data Type with Examples

M66 2025-07-22

How to Output the Data Type of a Variable in PHP

In PHP development, determining a variable’s data type is a common need, especially during debugging. PHP provides the built-in gettype() function, which returns information about a variable's type.

Basic Usage of the gettype() Function

gettype() is a function used to retrieve the data type of a variable. It returns a string that represents the type. This function is useful in debugging, logic checks, and type verification.

Example Code


<?php
$name = "John Doe";
echo gettype($name); // Output: string
?>

Possible Return Values of gettype()

The function can return one of the following type names:

  • string
  • integer
  • float (or double)
  • boolean
  • array
  • object
  • resource
  • NULL

For example:


<?php
$number = 100;
echo gettype($number); // Output: integer

$flag = true;
echo gettype($flag); // Output: boolean

$data = null;
echo gettype($data); // Output: NULL
?>

Things to Keep in Mind

  • gettype() only returns the type, not the value of the variable.
  • If the variable is an object, the function returns "object" without specifying the class name.
  • If the variable is undefined or null, it returns "NULL".
  • It's a very helpful function when you need quick type checking during debugging or troubleshooting.

Conclusion

Using gettype() in PHP helps you determine variable types quickly and clearly. It's especially useful in dynamically typed contexts where variable content isn't always obvious. Every PHP developer should be familiar with this simple yet powerful tool.