gettype

(PHP 4, PHP 5, PHP 7, PHP 8)

gettypeВозвращает тип переменной

Описание

gettype(mixed $value): string

Возвращает тип PHP-переменной value. Для проверки типа переменной используйте функции is_*.

Список параметров

value

Проверяемая переменная.

Возвращаемые значения

Возможными значениями возвращаемой строки являются:

  • "boolean"
  • "integer"
  • "double" (по историческим причинам в случае типа float возвращается "double", а не просто "float")
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" с PHP 7.2.0
  • "NULL"
  • "unknown type"

Список изменений

Версия Описание
7.2.0 Для закрытых ресурсов теперь возвращается 'resource (closed)'. Ранее для закрытых ресурсов возвращалось 'unknown type'.

Примеры

Пример #1 Пример использования gettype()

<?php

$data 
= array(11.NULL, new stdClass'foo');

foreach (
$data as $value) {
    echo 
gettype($value), "\n";
}

?>

Результатом выполнения данного примера будет что-то подобное:

integer
double
NULL
object
string

Смотрите также

  • get_debug_type() - Gets the type name of a variable in a way that is suitable for debugging
  • settype() - Задаёт тип переменной
  • get_class() - Возвращает имя класса, к которому принадлежит объект
  • is_array() - Определяет, является ли переменная массивом
  • is_bool() - Проверяет, является ли переменная булевой
  • is_callable() - Проверяет, может ли значение переменной быть вызвано в качестве функции
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_int() - Проверяет, является ли переменная целым числом
  • is_null() - Проверяет, является ли значение переменной равным null
  • is_numeric() - Проверяет, является ли переменная числом или строкой, содержащей число
  • is_object() - Проверяет, является ли переменная объектом
  • is_resource() - Проверяет, является ли переменная ресурсом
  • is_scalar() - Проверяет, является ли переменная скалярным значением
  • is_string() - Проверяет, является ли переменная строкой
  • function_exists() - Возвращает true, если указанная функция определена
  • method_exists() - Проверяет, существует ли метод в данном классе

add a note add a note

User Contributed Notes 11 notes

up
0
PPKu-N0-SPAM-schy at mediasoft-berlin dot de
13 years ago
After some testing I found a bug in my function "myGetType":
The check for "is_callable" was done before "is_string", so that something like <?php echo myGetType("max"); ?> would output: "function reference" instead of "string"

"is_callable" and "is_string" can't be checked together in this method, so I've removed the check for is_callable because it's a very rare usage case and if it's a valid string the check for is_callable never executes because is_string would be reached first (or vice-versa).

So here is the new function without "is_callable"-Check:
<?php
   
/**
     * Returns the type of the var passed.
     *
     * @param mixed $var Variable
     * @return string Type of variable
     */
   
function myGetType($var)
    {
        if (
is_array($var)) return "array";
        if (
is_bool($var)) return "boolean";
        if (
is_float($var)) return "float";
        if (
is_int($var)) return "integer";
        if (
is_null($var)) return "NULL";
        if (
is_numeric($var)) return "numeric";
        if (
is_object($var)) return "object";
        if (
is_resource($var)) return "resource";
        if (
is_string($var)) return "string";
        return
"unknown type";
    }
?>
up
-2
gilthansNOSPAM at gmail dot com
18 years ago
NaN and #IND will return double or float on gettype, while some inexistent values, like division by zero, will return as a boolean FALSE. 0 by the 0th potency returns 1, even though it is mathematically indetermined.

<?php
$number
= 5/0;
$number2 = sqrt(-3);
$number3 = pow(0, 0);
$number4 = 0/0;

echo
$number."<br />";
echo
$number2."<br />";
echo
$number3."<br />";
echo
$number4."<br />";
echo
"<br />";
echo
gettype($number)."<br />";
echo
gettype($number2)."<br />";
echo
gettype($number3)."<br />";
echo
gettype($number4);
?>

This will return:

-1.#IND
1

boolean
double
integer
boolean

0
1
1
0
PHP Warning: Division by zero in C\test.php on line 2 PHP Warning: Division by zero in C:\test.php on line 5
up
-4
langpavel at phpskelet dot org
12 years ago
This function returns string representation of type. This is generalization of get_class(). I try to order is_* tests by density of occurence, but is bad idea to use result of this call in conditions for performance reasons, usefull and better than gettype for debugging messages.
Note, that last line should not be never executed.
Also has no sense to make input parameter optional.

<?php
function get_type($var)
{
    if(
is_object($var))
        return
get_class($var);
    if(
is_null($var))
        return
'null';
    if(
is_string($var))
        return
'string';
    if(
is_array($var))
        return
'array';
    if(
is_int($var))
        return
'integer';
    if(
is_bool($var))
        return
'boolean';
    if(
is_float($var))
        return
'float';
    if(
is_resource($var))
        return
'resource';
   
//throw new NotImplementedException();
   
return 'unknown';
}
?>
up
-6
SoN9ne at gmail dot com
13 years ago
This is my work around for the gettype warning. Hope some find it useful.

<?php
   
/**
     * Returns the type of the passed var
     * - PHP warns against using gettype(), this is my workaround
     *
     * @param mixed $var
     * @return string
     */
   
function myGetType($var)
    {
        if (
is_array($var)) return "array";
        if (
is_bool($var)) return "boolean";
        if (
is_callable($var)) return "function reference";
        if (
is_float($var)) return "float";
        if (
is_int($var)) return "integer";
        if (
is_null($var)) return "NULL";
        if (
is_numeric($var)) return "numeric";
        if (
is_object($var)) return "object";
        if (
is_resource($var)) return "resource";
        if (
is_string($var)) return "string";
        return
"unknown type";
    }
?>

[EDITOR thiago NOTE: Code has been updated by PPKu-N0-SPAM-schy at mediasoft-berlin dot de]
up
-6
Wilson212
12 years ago
I did some benchmarking and your method here is alot slower then using the actual gettype(); (Using php 5.3.4)
up
-6
matt at appstate
19 years ago
Here is something that had me stumped with regards to gettype and is_object.
Gettype will report an incomplete object as such, whereas is_object will return FALSE.

<?php
if (!is_object($incomplete_obj)) {
   echo
'This variable is not an object, it is a/an ' . gettype($incomplete_obj);
}
?>

Will print:
This variable is not an object, it is a/an object
up
-4
wojciech dot fornal at gmail dot com
9 years ago
@langpavel at phpskelet dot org

Doesn't the gettype return the string already? Using get_class seems to be the only "useful" part of that solution. All that can be reduced to somewhere half in terms of the amount of code.
up
-5
samokspv1 at gmail dot com
5 years ago
Result from this post http://php.net/manual/en/function.gettype.php#56662 for new PHP 7.2.10:

<?php
$number
= 5/0;
$number2 = sqrt(-3);
$number3 = pow(0, 0);
$number4 = 0/0;

echo
$number."<br />";
echo
$number2."<br />";
echo
$number3."<br />";
echo
$number4."<br />";
echo
"<br />";
echo
gettype($number)."<br />";
echo
gettype($number2)."<br />";
echo
gettype($number3)."<br />";
echo
gettype($number4);
?>

This will return:
INF
NAN
1
NAN

double
double
integer
double
up
-7
skatebiker at hotmail dot com
16 years ago
In some rare cases a class instance object returns false when an object but gettype() returns "object".

<?php
$x
= new classvar();

$save = serialize($x);

// ......

$obj = unserialize($save);
// here sometimes is_object() returns FALSE
if (is_object($x) || gettype($x) === "object")
{
  
// ... do something
}
?>
up
-8
sneskid at hotmail dot com
17 years ago
I wrote my own gettype function by just using the default is_? functions, but it took twice as long as gettype... So I decided to use gettype with a twist.

Taking the warnings about gettype to heart, and depending on your custom needs, it's worthwhile to dynamically test the gettype result with a known variable, and link the result to a predefined result. Like so:

<?php
/*
dynamically create an array by using known variable types
link with a predefined value
*/
$R=array();
$R[gettype(.0)]='number';
$R[gettype(0)]='number';
$R[gettype(true)]='boolean';
$R[gettype('')]='string';
$R[gettype(null)]='null';
$R[gettype(array())]='array';
$R[gettype(new stdClass())]='object';

// what is
function wis_($v){
    global
$R;
    return
$R[gettype($v)];
}

echo
wis_('hello') . '<br/>'; // "string"
echo wis_(24) . '<br/>'; // "number"
echo wis_(0.24) . '<br/>'; // "number"
echo wis_(null) . '<br/>'; // "null"
echo wis_($R) . '<br/>'; // "array"
?>
You won't need to worry about changes in gettype's return strings in future versions.
If the result evaluates to false then you know the variable tested is some "other" type.

I also find these useful
<?php
function is_num($v){return (is_int($v) || is_double($v));}
function
is_box($v){return (is_array($v)||is_object($v));}

echo
is_num(null) . '<br/>'; // false
echo is_num(false) . '<br/>'; // false
echo is_num('123') . '<br/>'; // false
echo is_num(123) . '<br/>'; // true
echo is_num(123.0) . '<br/>'; // true
?>
up
-13
ddr-2kpp (at) web dot de
9 years ago
Hi there,

this fastest solution I found to identify a variable type without using gettype function:
<?PHP
function typeof($var) {
  if (
is_object($var))
    return
"object";

  if (
is_resource($var))
    return
"resource";

  return ((
$var === null) ? "null" :
      (((bool)
$var === $var) ? "bool" :
       (((float)
$var === $var) ? "float" :
        (((int)
$var === $var) ? "int" :
         (((string)
$var === $var) ? "string" :
             
"unknown"
         
)
         )
        )
       )
      );
}
?>
Maybe someone has a more elegant solution to check for object and resource types...

The complete script - including several identify- and timing functions follow:
#!/usr/bin/php
<?PHP
function typeof_trinary($var) {
  if (
is_object($var))
    return
"object";

  if (
is_resource($var))
    return
"resource";

  return ((
$var === null) ? "null" :
      (((bool)
$var === $var) ? "bool" :
       (((float)
$var === $var) ? "float" :
        (((int)
$var === $var) ? "int" :
         (((string)
$var === $var) ? "string" :
             
"unknown"
         
)
         )
        )
       )
      );
   }

function
typeof_if_query($var) {
  
  if (
is_object($var))
    return
"object";

  if (
is_resource($var))
    return
"resource";
 
  if ((bool)
$var === $var)
      return
"bool";

  if ((float)
$var === $var)
    return
"float";

  if ((int)
$var === $var)
    return
"int";

  if ((string)
$var === $var)
    return
"string";

  if (
null === $var)
    return
"null";

  return
"unknown";
}

function
typeof_gettype($var) {
    return \
gettype($var);
}

$var = 100;

echo
"start@ " . \date("Y-m-d H:i:s") . "\n";
echo
"\$var = $var - gettype(\$var) = " . gettype($var) . "\n\n";
$time = -\microtime(true);

echo
"typeof_if_query(\$var) = " . typeof_if_query($var) . "\n";
$time += \microtime(true);
echo
"duration: " . \sprintf("%0.10f",$time) . "\n\n";

$time = -\microtime(true);

echo
"typeof_gettype(\$var) = " . typeof_gettype($var) . "\n";
$time += \microtime(true);
echo
"duration: " . \sprintf("%0.10f",$time) . "\n\n";

$time = -\microtime(true);

echo
"typeof_trinary(\$var) = " . typeof_trinary($var) . "\n";
$time += \microtime(true);
echo
"duration: " . \sprintf("%0.10f",$time) . "\n\n";
?>

My console output - try the script several times!:
$ ./gettype.php
start@ 2015-01-10 01:10:37
$var = 100 - gettype($var) = integer

typeof_if_query($var) = int
duration: 0.0000500679

typeof_gettype($var) = integer
duration: 0.0000309944

typeof_trinary($var) = int
duration: 0.0000240803
To Top