PHP - Getting variable's type

Introduction

You can determine the type of a variable using PHP's gettype() function.

The function then returns the variable's type as a string.

In the following code, a variable is declared, and its type is tested with gettype().

Then, four different types of data are assigned to the variable, and the variable's type is retested with gettype() each time:

Demo

<?php
         $test_var; // Declares the $test_var variable without initializing it
         echo gettype( $test_var ) . " \n "; // Displays "NULL"
         $test_var = 15;
         echo gettype( $test_var ) . " \n "; // Displays "integer"
         $test_var = 8.23;
         echo gettype( $test_var ) . " \n "; // Displays "double"
         $test_var = "Hello, world!";
         echo gettype( $test_var ) . " \n "; // Displays "string"
?>/* w  w w . ja va2  s.c o  m*/

Result

The $test_var variable initially has a type of null, because it has been created but not initialized with an assigned value.

After setting $test_var's value to 15, its type changes to integer.

Setting $test_var to 8.23 changes its type to double.

Finally, setting $test_var to "Hello, world!" alters its type to string.

In PHP, a floating-point value is a value with a decimal point.

So if 15.0 was used instead of 15 in the preceding example, $test_var would become a double, rather than an integer.

More functions

You can test a variable for a specific data type using PHP's type testing functions:

Function Description
is_int( value ) Returns true if value is an integer
is_float( value ) Returns true if value is a float
is_string( value ) Returns true if value is a string
is_bool( value ) Returns true if value is a Boolean
is_array( value ) Returns true if value is an array
is_object( value ) Returns true if value is an object
is_resource( value )Returns true if value is a resource
is_null( value )Returns true if value is null

Related Topic