Type checking with gettype()
Learn to find a variable's type with the gettype() function.
The gettype() function
gettype() returns a variable's type as a string. Example: echo gettype(42); prints integer.
Common return values: string, integer, double (for float), boolean and NULL.
Note: PHP returns double for the float type for historical reasons. So gettype(3.14) prints double.
This function is useful for finding type-related bugs while debugging.
Type strings and what to watch for
The strings returned by gettype() are fixed:
"string"— the text type."integer"— whole numbers."double"— fractional numbers (float)."boolean"— true or false."NULL"— no value (uppercase).
These strings are case-sensitive. When comparing, you must match them exactly.
Later you will meet is_string(), is_int() and other handy helpers.
Exercise Print the type of three variables
Assign "Book" to $name, 12 to $count, and 49.99 to $price. Print the gettype() output for each variable on its own line.
Show example solution
On each line write echo gettype(...) . "\n";.
Example solution:
<?php
$name = "Book";
$count = 12;
$price = 49.99;
echo gettype($name) . "\n";
echo gettype($count) . "\n";
echo gettype($price) . "\n";
Test yourself
-
What does gettype(42) return?
echo gettype(42);- "int"
- "integer"
- "number"
- "42"
Show answer
"integer" — Correct! PHP returns "integer" for whole numbers.
-
Print the type of $score
echo ____($score);Show answer
echo gettype($score); -
Match each value to its gettype output
- 42
- integer
- 3.14
- double
- "book"
- string
- null
- NULL