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
gettypeto return the exact class name for objects; it returns "object" instead. - Confusing
gettypewithvar_dumporget_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 gettype | Description |
|---|---|
| boolean | A true or false value |
| integer | A whole number |
| double | A floating-point number (decimal) |
| string | A sequence of characters |
| array | A collection of values |
| object | An instance of a class |
| resource | A special variable holding a resource |
| NULL | A variable with no value |
| unknown type | Type 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.