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.


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’.

    function func($par) {
        echo("Data type of '".$par."' is '".gettype($par)."'.\n");


Data type of '50' is 'integer'.
Data type of '2.5' is 'double'.
Data type of 'hello' is 'string'.
Data type of '' is 'NULL'.

PHP MCQ - Multiple Choice Questions and AnswersPHP Questions and Answers – Object-Oriented OOP – Part 1This collection of PHP Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Object-Oriented OOP”.   1. The concept of…Read More

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.

    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
    // square with 2 as a string, produces an error
    catch (Exception $e) 


Invalid parameter passed. Integer was expected, string was given.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *