How to Get Variable Data Type in PHP Using gettype

This article explains how to use the built-in gettype() function in PHP to determine the exact data type of any variable. You will learn the syntax of the function, the specific string values it returns for different data types, and see practical code examples demonstrating its usage.

Understanding the gettype() Function

In PHP, gettype() is a built-in function used to retrieve the data type of a helper variable. It takes a single variable as an argument and returns a string representing its type.

Syntax

gettype(mixed $value): string

Possible Return Values

The gettype() function will return one of the following standard strings depending on the type of the variable passed to it:


Practical Code Examples

Here is how you can use gettype() to inspect different types of variables in your PHP code:

<?php
// Define various variable types
$itemString = "Hello, World!";
$itemInteger = 42;
$itemFloat = 12.34;
$itemBoolean = true;
$itemArray = [1, 2, 3];
$itemNull = null;

// Retrieve and print their data types
echo gettype($itemString) . "\n";  // Outputs: string
echo gettype($itemInteger) . "\n"; // Outputs: integer
echo gettype($itemFloat) . "\n";   // Outputs: double
echo gettype($itemBoolean) . "\n"; // Outputs: boolean
echo gettype($itemArray) . "\n";   // Outputs: array
echo gettype($itemNull) . "\n";    // Outputs: NULL
?>

Best Practices: gettype() vs. is_* Functions

While gettype() is highly useful for debugging and logging, it is not recommended for conditional validation logic (like if statements). String comparisons can be slow and prone to typos.

For type validation, PHP provides specialized is_* helper functions which return a boolean (true or false):

These specific functions are faster, cleaner, and less prone to errors during development.