We use gettype and get_debug_type checks to find out what kind of data a variable holds. This helps us understand and control our program better.
0
0
Gettype and typeof checks in PHP
Introduction
When you want to check if a variable is a number or a string before doing math or text work.
When debugging to see what type of data a variable contains.
When writing functions that behave differently based on the input type.
When validating user input to make sure it matches expected types.
When converting data and you want to confirm the original type first.
Syntax
PHP
<?php // Using gettype $type = gettype($variable); // Using get_debug_type (PHP 8.0+) $type = get_debug_type($variable); ?>
gettype returns a string describing the type, like 'integer', 'string', 'array'.
get_debug_type is a newer feature (PHP 8.0+) that returns a string representing the precise type, like 'int', 'float', 'bool'.
Examples
This shows how gettype returns the type name as a string.
PHP
<?php $x = 10; echo gettype($x); // prints 'integer' ?>
Checking a string variable with gettype.
PHP
<?php $y = "hello"; echo gettype($y); // prints 'string' ?>
get_debug_type returns a string with the precise type name.
PHP
<?php // Using get_debug_type in PHP 8.0+ $z = 3.14; $type = get_debug_type($z); echo $type; // prints 'float' ?>
Sample Program
This program loops through different values and prints their types using both gettype and get_debug_type (if PHP version supports it).
PHP
<?php // Sample program to show gettype and get_debug_type $values = [123, "text", 3.14, true, [1, 2, 3]]; foreach ($values as $val) { echo "Value: "; print_r($val); echo " - gettype: " . gettype($val) . "\n"; if (PHP_VERSION_ID >= 80000) { $type = get_debug_type($val); echo " - get_debug_type: " . $type . "\n"; } echo "\n"; } ?>
OutputSuccess
Important Notes
gettype returns 'double' for floating point numbers, but get_debug_type returns 'float'.
get_debug_type is only available in PHP 8.0 and later.
Use gettype for simple type checks in older PHP versions.
Summary
gettype returns the type of a variable as a string.
get_debug_type returns a more precise type name as a string (PHP 8.0+).
Both help you understand what kind of data you are working with.