Usually, many variables are used within a program, and they are associated with particular data types. In many coding scenario cases, it is sometimes necessary to know the data type of a particular variable. This is why PHP provides a built-in function that helps to obtain the data type of a variable. In this tutorial, you will learn about the gettype() function of PHP.
Get the Type of a Variable Using gettype() Function
The gettype() function is an inbuilt library function in PHP used to obtain the data type of an existing variable. It helps the programmer to find the type of data associated with a particular variable that is needed in the program itself.
The syntax of using this function is:
string gettype( mixed $variable_name)
This function only accepts a variable that needs to be checked to know the type of variable. This function returns the name of the data type as a string value.
The gettype() Function Example
An example of using this gettype() function is as follows:
<?php echo gettype("W3schools.in").'<br>'; echo gettype('').'<br>'; echo gettype(null).'<br>'; echo gettype(false).'<br>'; echo gettype(array()).'<br>'; echo gettype(new stdclass()).'<br>'; echo gettype(123456).'<br>'; ?>
string string NULL boolean array object integer
Practical Scenario to Use for PHP gettype() Function
Usually, we do not know when this function will be used, so here are some scenarios where this function would be fit to use.
Various complex situations arise when programming a large application.
- Suppose a user enters a value that does not match the validation of the data type, and you want to indicate to the user that he is entering the wrong data type in the input.
- Another situation where this function becomes necessary is - while debugging a program to find an error. In some cases, the programmer needs to track the type of a variable value at a particular point in the running program. In this case, the programmer can use the gettype() function between break-points to find the current data type of a variable.