How do you determine the data type of a variable in PHP?
PHP is more tolerant than other programming languages and does not require a fixed data type to be specified for a variable. In fact, there is not even an opportunity to do so. Nevertheless, the value of each variable has a data type that influences the processing of this value. For example, adding integers behaves differently than adding strings.
gettype()
To find out what data type the value of a variable has, gettype($var) can be used. This function returns one of the following string, which correspond to the known data types in PHP: ‘boolean’, ‘integer’, ‘double’, ‘string’, ‘array’, ‘object’, ‘resource’, ‘NULL’, ‘unknown type’. Floats are represented by ‘double’.
<?php function func($par) { echo("Data type of '".$par."' is '".gettype($par)."'.\n"); } func(50); func(2.5); func("hello"); func(null); ?>
Output:
Data type of '50' is 'integer'. Data type of '2.5' is 'double'. Data type of 'hello' is 'string'. Data type of '' is 'NULL'.
[st_adsense]
is_* functions
The function gettype() should only be used to output the datatype of a variable. Testing for special datatypes – with this function – is not recommended, because the returns may change at some point. Instead, the functions is_boolean($var), is_string($var), is_float($var), is_array($var), is_object($var), is_resource($var) and is_null($var) should be used.
<?php function square($val) { // Only integers or floats should be squared by this function // an error is thrown for all other data types. if (!is_int($val) && !is_float($val)) { throw new Exception('Invalid parameter passed. ' .'Integer was expected, '.gettype($val).' was given.'); } return ($val * $val); } // square with 2 as a number var_dump(square(2)); // square with 2 as a string, produces an error try { var_dump(square("2")); } catch (Exception $e) { echo($e->getMessage()); } ?>
Output:
int(4) Invalid parameter passed. Integer was expected, string was given.[st_adsense]