The PHP gettype() function returns the type of a variable as a string. It identifies the variable's data type, such as string, integer, array, boolean, etc., allowing developers to check and handle different data types dynamically.
Syntax:
string gettype ( $var )
Parameter: This function accepts a single parameter $var. It is the name of the variable which is needed to be checked for the type of variable.
Return Value:
This function returns a string-type value. Possible values for the returned string are:
- boolean
- integer
- double (for historical reasons "double" is returned in case of float)
- string
- array
- object
- resource
- NULL
- unknown type
Below programs illustrate the gettype() function in PHP:
Example 1: In this example we demonstrates the gettype() function, which identifies and prints the data types of various variables, including boolean, integer, double, string, array, object, null, and resource types.
php
<?php
// PHP program to illustrate gettype() function
$var1 = true;
// boolean value
$var2 = 3;
// integer value
$var3 = 5.6;
// double value
$var4 = "Abc3462";
// string value
$var5 = array(1, 2, 3);
// array value
$var6 = new stdClass;
// object value
$var7 = NULL;
// null value
$var8 = tmpfile();
// resource value
echo gettype($var1)."\n";
echo gettype($var2)."\n";
echo gettype($var3)."\n";
echo gettype($var4)."\n";
echo gettype($var5)."\n";
echo gettype($var6)."\n";
echo gettype($var7)."\n";
echo gettype($var8)."\n";
?>
Outputboolean
integer
double
string
array
object
NULL
resource
Example 2: In this example we use the gettype() function to identify and print the data types of variables, including a string, integer (modulus operation), integer (power), double (square root), and double.
php
<?php
// PHP program to illustrate gettype() function
$var1 = "GfG";
$var2 = 10 % 7;
$var3 = pow(10, 2);
$var4 = pow(10, 0.5);
$var5 = sqrt(9);
echo gettype($var1)."\n";
echo gettype($var2)."\n";
echo gettype($var3)."\n";
echo gettype($var4)."\n";
echo gettype($var5);
?>
Outputstring
integer
integer
double
double