Get type of php var

PHP: как узнать тип переменной: 2 способа

Типы данных в языке PHP используются для хранения различных видов данных или значений. В последних версиях язык поддерживает 8 встроенных типов данных. Все их можно разделить на три вида:

1. «Скалярные» или простые типы.

Простые типы

В PHP существует четыре простых типа данных:

  • булев (boolean),
  • целое число (integer),
  • дробное число (float),
  • строка (string).

Сложные или составные типы

Также в PHP есть два основных типа данных:

Специальные типы

В языке предусмотрено два таких типа данных:

Часто нужно менять данные с одного типа на другого. Или, например, просто узнавать тип данных для какого-либо объекта. В этих и множестве других случаев помогут две функции: gettype и settype.

gettype. Пример

Функция gettype() возвращает тип данных переменной, переданной ей в качестве аргумента. При этом она может получить вообще любой тип переменной.

Необходимо сохранить возвращаемое значение в переменной и вывести его на экран. Например, вот так

"; $mini = 3.2; echo gettype($mini) ."
"; $dini = "Privet"; echo gettype($dini) ."
"; $bini = array(); echo gettype($bini) ."
"; $gini = array("cat", "dog", "horse"); echo gettype($gini) ."
"; $tini = NULL; echo gettype($tini) ."
"; $zini = false; echo gettype($zini) ."
"; ?>

Вывод примера

Подробнее о функции

Функция gettype() — это встроенная функция в PHP для получения типа переменной.

Для проверки типа текущей переменной используется следующий синтаксис:

Параметры: принимает один аргумент $var. Это название переменной, тип которого мы и хотим проверить.

Возвращаемое значение: строка, описывающая тип данных:

  • boolean.
  • NULL.
  • integer.
  • resource.
  • double (возвращается, если аргумент является дробным числом).
  • object.
  • array.
  • unknown type (неизвестный тип).

Пример использование функции ниже:

Вывод примера

settype. Как установить тип для переменной

settype() используется для изменения типа переменной — с текущего на необходимый. Функция принимает два параметра:

  1. Имя переменной, которую нужно преобразовать.
  2. Тип, к которому нужно преобразовать переменную.
"; $mini = 4.3; settype($mini,'integer'); echo gettype($mini) . "
"; $dini = "Hi bears"; settype($dini,'array'); var_dump($dini); echo"
"; echo gettype($dini) . "
"; $gini = array("red", "green", "blue"); settype($gini,'string'); echo gettype($gini) . ";"; ?>
string integer array(1) < [0]=>string(12) "Hi bears" > array string;

Подробнее о функции

Функция settype() применяется для того, чтобы установить тип переменной или изменить тип уже существующей.

Переменная — один из самых частых объектов, которым оперирует программист в PHP и других языках.

boolean settype($variable_name, $type)

Параметры: принимает два параметра:

  • $variable_name: имя переменной.
  • $type: строка с именем устанавливаемого типа. Возможные значения: «boolean» или «bool», «integer» или «int», «float» или «double», «string», «array», «object», «null».

Возвращаемое значение: TRUE, если преобразование типов переменной прошло успешно, и FALSE — в обратном случае.

Бонус. Специальные функции

  • is_object($a): вернет true, если $a содержит ссылку на какой то объект.
  • is_bool($a): вернет true, если в $a хранится булево значение.
  • is_integer($a): вернет true, если в $a записано целое число.
  • is_array($a): вернет true, если $a является массивом.
  • is_string($a): вернет true, если $a содержит строку.
  • is_null($a): вернет true, если $a представляет null.
  • is_double($a): вернет true, если $a является дробным числом.
  • is_scalar($a): вернет true, если $a является простым типом данных, например, представляет из себя логическое значение или строку.
  • is_numeric($a): возвращает true, если $a является действительным, либо же целым числом. Также true будет возвращен в случае, когда переменная представляет из себя строковое представление числа.

Немного о преобразовании

PHP умеет автоматически преобразовывать разные типы переменных друг в друга. Но возможность задать явное преобразование также предусмотрена в языке.

Изучение типов переменных принесет вам пользу в долгосрочной перспективе. Ну а чтобы пользы было ещё больше — успейте записаться на курс бэкенд-разработчик от Loft.

Допустим нам нужно изменить «false» в int. Чтобы это сделать вы можете использовать, например, такой подход:

$boolVar = false; $intVar = (int)$boolVar; // 0 echo "boolVar = $boolVar
intVar = $intVar";

Обратите внимание: значение находится внутри переменной $intVar.

Вы можете задавать явное преобразование в следующие типы объектов:

Источник

gettype

Returns the type of the PHP variable value . For type checking, use is_* functions.

Parameters

The variable being type checked.

Return Values

  • «boolean»
  • «integer»
  • «double» (for historical reasons «double» is returned in case of a float , and not simply «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» as of PHP 7.2.0
  • «NULL»
  • «unknown type»

Changelog

Version Description
7.2.0 Closed resources are now reported as ‘resource (closed)’ . Previously the returned value for closed resources were ‘unknown type’ .

Examples

Example #1 gettype() example

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

The above example will output something similar to:

integer double NULL object string

See Also

  • get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
  • settype() — Set the type of a variable
  • get_class() — Returns the name of the class of an object
  • is_array() — Finds whether a variable is an array
  • is_bool() — Finds out whether a variable is a boolean
  • is_callable() — Verify that a value can be called as a function from the current scope.
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_null() — Finds whether a variable is null
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_object() — Finds whether a variable is an object
  • is_resource() — Finds whether a variable is a resource
  • is_scalar() — Finds whether a variable is a scalar
  • is_string() — Find whether the type of a variable is string
  • function_exists() — Return true if the given function has been defined
  • method_exists() — Checks if the class method exists

User Contributed Notes 2 notes

Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string — string // OK
int — integer // Type mismatch
bool — boolean // Type mismatch
array — array // OK

Same as for «boolean» below, happens with integers. gettype() return «integer» yet proper type hint is «int».

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.

Источник

gettype

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

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

Переменная, у которой проверяется тип.

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

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

Примеры

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

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

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

integer double NULL object string

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

  • 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() — Проверяет, существует ли метод в данном классе

Источник

gettype

Returns the type of the PHP variable value . For type checking, use is_* functions.

Parameters

The variable being type checked.

Return Values

Possible values for the returned string are:

  • «boolean»
  • «integer»
  • «double» (for historical reasons «double» is returned in case of a float , and not simply «float» )
  • «string»
  • «array»
  • «object»
  • «resource»
  • «resource (closed)» as of PHP 7.2.0
  • «NULL»
  • «unknown type»

Changelog

Version Description
7.2.0 Closed resources are now reported as ‘resource (closed)’ . Previously the returned value for closed resources were ‘unknown type’ .

Examples

Example #1 gettype() example

$data = array( 1 , 1. , NULL , new stdClass , ‘foo’ );

foreach ( $data as $value ) echo gettype ( $value ), «\n» ;
>

The above example will output something similar to:

integer double NULL object string

See Also

  • get_debug_type() — Gets the type name of a variable in a way that is suitable for debugging
  • settype() — Set the type of a variable
  • get_class() — Returns the name of the class of an object
  • is_array() — Finds whether a variable is an array
  • is_bool() — Finds out whether a variable is a boolean
  • is_callable() — Verify that a value can be called as a function from the current scope.
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_null() — Finds whether a variable is null
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_object() — Finds whether a variable is an object
  • is_resource() — Finds whether a variable is a resource
  • is_scalar() — Finds whether a variable is a scalar
  • is_string() — Find whether the type of a variable is string
  • function_exists() — Return true if the given function has been defined
  • method_exists() — Checks if the class method exists

Источник

PHP gettype() Function

The gettype() function returns the type of a variable.

Syntax

Parameter Values

Technical Details

Return Value: The type as a string. Can be one of the following values: «boolean», «integer», «double», «string», «array», «object», «resource», «NULL», «unknown type»
Return Type: String
PHP Version: 4.0+
PHP Changelog: PHP 7.2: Closed resources are now returned as «resource (closed)». Earlier, the returned value was «unknown type».

❮ PHP Variable Handling Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Читайте также:  Add to queue python
Оцените статью