Get type of data php

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

Источник

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() — Проверяет, существует ли метод в данном классе
Читайте также:  Php hidden file upload

Источник

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.

Источник

PHP gettype() Function

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

Читайте также:  Css как сделать ссылку некликабельной

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.

Источник

How to Check a Variable’s Type in PHP

So, you want to know how to determine a variable’s data type in PHP? Read on; this tutorial will show you how!

Welcome to today’s PHP tutorial, where we’ll be diving into the world of PHP yet again, and learning how to get the type of a variable.

If you’ve ever found yourself scratching your head and wondering about the kind of data you’re working with in PHP, that’s exactly what we’re going to be covering today. Awesome, let’s get started!

Checking a Variable’s Type

To determine the type of a variable in PHP, we can use the built-in gettype() function. This function takes a single parameter, which is the variable that you want to check, and returns a string representing that variable’s data type.

$number = 42; gettype($number); // integer

In the above example, we have a variable called $number , which contains the value 42 . To check its type, we call gettype($number) and it returns the string «integer» .

Similarly, if we have a variable $string containing the value «Hello, world!» , calling gettype($string) will return «string» , like so:

$string = "Hello, world!"; gettype($string); // string

Getting to Know the gettype() Function

There are only so many data types in PHP, which means that the gettype() function will return a limited set of possible types, which include:

  • «boolean» for boolean values ( true or false )
  • «integer» for integer values
  • «float» for floating-point values
  • «double» for floating-point values (same as «float» )
  • «string» for string values
  • «array» for arrays
  • «object» for objects
  • «resource» for resources
  • «NULL» for null values
  • «unknown type» for any other type of value

Alternative Methods

In addition to gettype() , PHP also provides the is_* family of functions that allow us to check whether a variable is of a certain type.

For example, is_int($number) will return true if $number is an integer and false otherwise. Here’s an example:

$number = 42; if (is_int($number))  echo "The variable's data type is an integer."; > else  echo "The variable's data type is not an integer."; >

This function is helpful when you need to verify if a given variable is of a certain data type.

By Dim Nikov

Editor of Maker’s Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment Cancel reply

  • How to Wait for an Element to Exist in JavaScript July 13, 2023
  • How to Check If a Function Exists in JavaScript July 13, 2023
  • How to Remove Numbers From a String With RegEx July 13, 2023
  • How to Check If a String Is a Number in JavaScript July 13, 2023
  • How to Insert a Variable Into a String in PHP July 12, 2023

We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.

Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.

These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Оцените статью