0
0
PhpHow-ToBeginner · 3 min read

How to Use gettype in PHP: Syntax and Examples

In PHP, use the gettype function to find the type of any variable. It returns a string describing the variable's type, such as "integer", "string", or "array".
📐

Syntax

The gettype function takes one argument, the variable you want to check, and returns its type as a string.

  • gettype(mixed $variable): string
  • $variable: The variable whose type you want to find.
  • Returns a string like "boolean", "integer", "double", "string", "array", "object", "resource", "NULL", or "unknown type".
php
gettype($variable);
💻

Example

This example shows how to use gettype to print the type of different variables.

php
<?php
$number = 42;
$text = "Hello";
$list = [1, 2, 3];
$flag = true;

echo gettype($number) . "\n";  // integer
echo gettype($text) . "\n";    // string
echo gettype($list) . "\n";    // array
echo gettype($flag) . "\n";    // boolean
?>
Output
integer string array boolean
⚠️

Common Pitfalls

Some common mistakes when using gettype include:

  • Expecting gettype to return the exact class name for objects; it returns "object" instead.
  • Confusing gettype with var_dump or get_class, which provide more detailed info.
  • Not handling the "unknown type" return value, which can happen with some special variables.
php
<?php
// Wrong: expecting class name from gettype
class Dog {}
$dog = new Dog();
echo gettype($dog); // outputs 'object', not 'Dog'

// Right: use get_class for class name
echo get_class($dog); // outputs 'Dog'
?>
Output
object Dog
📊

Quick Reference

Type Returned by gettypeDescription
booleanA true or false value
integerA whole number
doubleA floating-point number (decimal)
stringA sequence of characters
arrayA collection of values
objectAn instance of a class
resourceA special variable holding a resource
NULLA variable with no value
unknown typeType could not be determined

Key Takeaways

Use gettype(variable) to get the type of any PHP variable as a string.
gettype returns general types like 'object' but not specific class names.
For objects, use get_class to get the exact class name.
Remember gettype can return 'unknown type' for special cases.
gettype is useful for debugging and type checking in PHP scripts.