In this tutorial, you shall learn how to get the type of a given variable in PHP using gettype() function, with example programs.

PHP – Get Type of Variable

To get the type of a variable in PHP, call gettype() function and pass the variable as argument.

gettype() inbuilt function takes value, expression, or a variable as an argument, and returns a string specifying the type of given argument.

Examples

ADVERTISEMENT

1. Get the type of variable x

In the following example, we initialize a variable $x with integer value, and get the type of $x programmatically using gettype() function.

PHP Program

<?php
$x = 25;
echo gettype($x);
?>

Output

PHP - Get Type of Variable

2. Get the type of a string literal

In the following example, we get the type of the value 'hello world' programmatically using gettype() function.

PHP Program

<?php
echo gettype('hello world');
?>

Output

PHP - Get Type of Value

2. Get the type of an expression

In the following example, we get the type of the expression '$x + $y' where $x is an integer, and $y is a double. Of course, the expression has to evaluate to a value, and we are using gettype() function to get the type of that resulting value of the expression.

PHP Program

<?php
$x = 4;
$y = 2.47;
echo gettype($x + $y);
?>

Output

PHP - Get Type of Expression

Conclusion

In this PHP Tutorial, we learned how to get the type of a variable, a value, or an expression, using gettype() function, with examples.