0
0
PhpHow-ToBeginner · 3 min read

How to Check Data Type in PHP: Simple Guide

In PHP, you can check the data type of a variable using the 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
<?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
<?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";
}
?>
Output
Type of var1: integer Type of var2: string Type of var3: array var2 is a string var3 is an array
⚠️

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
<?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)
?>
Output
bool(false) bool(true)
📊

Quick Reference

FunctionDescription
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)

Key Takeaways

Use gettype() to get the data type of any variable as a string.
Use is_* functions like is_int() or is_string() to check specific types with true/false results.
Remember gettype() returns a string, not a boolean.
Loose comparisons can mislead type checks; prefer is_* functions for accuracy.
Casting variables can help when you expect a certain type but have a string or other type.