PHP gettype() Function
The PHP gettype() function returns the type of the PHP variable.
Syntax
gettype(variable)
Parameters
variable |
Required. Specify the variable to check. |
Return Value
Returns the type of the variable. Possible values for the returned string are:
- "boolean"
- "integer"
- "double" (for historical reasons "double" is returned in case of a float)
- "string"
- "array"
- "object"
- "resource"
- "resource (closed)"
- "NULL"
- "unknown type"
Note: As of PHP 7.2.0, closed resources is reported as resource (closed). Previously the returned value for closed resources were unknown type.
Example: gettype() example
The example below shows the usage of gettype() function.
<?php echo "gettype(10): ".gettype(10)."\n"; echo "gettype(10.5): ".gettype(10.5)."\n"; echo "gettype(1e5): ".gettype(1e5)."\n"; echo "gettype('10.5'): ".gettype('10.5')."\n"; echo "gettype('xyz'): ".gettype('xyz')."\n"; echo "gettype(false): ".gettype(false)."\n"; echo "gettype(null): ".gettype(null)."\n"; echo "gettype(array()): ".gettype(array())."\n"; echo "gettype([]): ".gettype([])."\n"; ?>
The output of the above code will be:
gettype(10): integer gettype(10.5): double gettype(1e5): double gettype('10.5'): string gettype('xyz'): string gettype(false): boolean gettype(null): NULL gettype(array()): array gettype([]): array
Example: using with object and resource variables
Consider the example below where this function is used with object and resource variables. Lets assume that we have a file called test.txt in the current working directory.
<?php $file = fopen("test.txt","r"); echo gettype($file)."\n"; fclose($file); echo gettype($file)."\n"; $iter = new ArrayIterator(); echo gettype($iter)."\n"; ?>
The output of the above code will be:
resource resource (closed) object
❮ PHP Variable Handling Reference