Sometimes you need to ask a value: “what are you?” PHP has a family of functions for that, and each one returns true or false.
| Function | True when the value is… |
|---|---|
is_int($v) | an integer |
is_float($v) | a float |
is_string($v) | a string |
is_bool($v) | true or false |
is_array($v) | an array |
is_object($v) | an object |
is_null($v) | null |
is_numeric($v) | a number or a numeric string like "12.5" |
is_callable($v) | something that can be called as a function |
is_iterable($v) | an array or something you can loop over |
<?php
var_dump(is_int(5));
var_dump(is_int("5"));
var_dump(is_string("5"));
var_dump(is_numeric("5"));
var_dump(is_numeric("5 apples"));
var_dump(is_array([1, 2]));
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Why is_numeric() is useful
Form data always arrives as strings. is_int("25") is false, but is_numeric("25") is true, so it is the right test for typed input.
Type in a message
get_debug_type() gives a readable name that is great for error messages.
<?php
function describe(mixed $value): string
{
return "Got " . get_debug_type($value);
}
echo describe(5) . "\n";
echo describe("text") . "\n";
echo describe([1, 2]) . "\n";
echo describe(null);
Got int
Got string
Got array
Got null
Checking against a list of types
<?php
$value = "42";
if (is_int($value) || is_float($value)) {
echo "A real number";
} elseif (is_string($value) && is_numeric($value)) {
echo "A number written as text";
} else {
echo "Something else";
}
A number written as text