gettype()

Description

The gettype() function returns the data type of a passed expression as a string. An expression of any data type can be passed to gettype(). As this function is inefficient to execute, it should only be used for debugging. For runtime data type checking, use the is_* functions.

Syntax


string gettype( mixed $expr );

Parameters

$expr
Expression for which the type is to be returned.

Return Value

string
The returned string can have one of the following values:

  • “boolean” if $expr is of type boolean
  • “integer” if $expr is of type integer
  • “double” if $expr is of type float
  • “string” if $expr is of type string
  • “array” if $expr is an array
  • “object” if $expr is an object
  • “resource” if $expr is a resource
  • “NULL” if $expr is null
  • “unknown type” if the type of $expr cannot be determined

Examples

1. Printing the Data Types

In this example, a variable of each data type is created by assigning it a literal value of the associated type. Then, the gettype() function is called for each of the variables. The $resourceVal variable assignment on line 9 assumes that a file called data.txt exists in the current directory. The fopen() function, if successful, returns a resource type representing a handle to the open file.

<?php
$boolVal     = true;
$intVal      = 6;
$doubleVal   = 3.14;
$stringVal   = "Hello";
$arrayVal    = array( 1, "two", 3.4 );
$objectVal   = new stdClass;
$nullVal     = null;
$resourceVal = fopen("./data.txt", "r");

echo gettype( $boolVal )     . "\n";
echo gettype( $intVal )      . "\n";
echo gettype( $doubleVal )   . "\n";
echo gettype( $stringVal )   . "\n";
echo gettype( $arrayVal )    . "\n";
echo gettype( $objectVal )   . "\n";
echo gettype( $nullVal )     . "\n";
echo gettype( $resourceVal ) . "\n";
fclose($resourceVal);
echo gettype( $resourceVal ) . "\n";
?>

The output of the program is shown below. Note the following:

  • Each of the data type values shown is a string.
  • On line 3 “double” is returned instead of “float” for historical reasons.
  • Prior to closing the file, gettype($resourceVal) returns resource and after closing the file the same call returns unknown type.
boolean
integer
double
string
array
object
NULL
resource
unknown type

2. Erroneous Assignment

In this example, the file data.txt does not exist in the directory. This causes the fopen() function to error and $resourceVal to get the Boolean value of false.

<?php
$resourceVal = fopen("./data.txt", "r");
echo gettype( $resourceVal ), "\n";
if ( !$resourceVal )
  echo "Value is false\n";
?>

This program produces the following output:

PHP Warning:  fopen(./data.txt): failed to open stream: No such file or directory in /home/charlie/php/test.php on line 2
boolean
Value is false

3. Passing a Function Reference

[Need example…]

See Also

fopen()
get_resource_type()

References