Inspecting Types

Inspecting and Converting Types

gettype() returns historical names such as integer and double; get_debug_type() (PHP 8.0) returns the names you write in declarations, or an object's class, so use it in error messages. Each is_*() test (is_int(), is_string(), is_null() and the rest) checks one type; is_numeric() also accepts numeric strings with spaces around them.

Inspecting a value, then converting it (inspect.php)PHP
<?php
foreach ([42, ' 42 ', null, new DateTime()] as $v) {
    printf("%-9s %-8s numeric: %s\n", get_debug_type($v), gettype($v),
        var_export(is_numeric($v), true));
}
var_dump((int) '42abc', filter_var('42abc', FILTER_VALIDATE_INT));
Output
int       integer  numeric: true
string    string   numeric: true
null      NULL     numeric: false
DateTime  object   numeric: false
int(42)
bool(false)

Convert with the casts (int), (float), (string), (bool), (array) and (object), or with intval($s, $base), floatval(), strval(), boolval() and settype(). A cast from a string never fails, so (int) '42abc' is quietly 42: fine for trusted values, wrong for user input, where filter_var() returns false instead (filter_var).