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.
Here’s an example:
$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
orfalse
)"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.