CodeBlanks Logo Icon CodeBlanks

Type checking with gettype()

PHP course · Beginner · Lesson 16/116

Learn to find a variable's type with the gettype() function.

The gettype() function

gettype() returns a variable's type as a string. Example: echo gettype(42); prints integer.

Common return values: string, integer, double (for float), boolean and NULL.

Note: PHP returns double for the float type for historical reasons. So gettype(3.14) prints double.

This function is useful for finding type-related bugs while debugging.

Type strings and what to watch for

The strings returned by gettype() are fixed:

  • "string" — the text type.
  • "integer" — whole numbers.
  • "double" — fractional numbers (float).
  • "boolean" — true or false.
  • "NULL" — no value (uppercase).

These strings are case-sensitive. When comparing, you must match them exactly.

Later you will meet is_string(), is_int() and other handy helpers.

Exercise Print the type of three variables

Assign "Book" to $name, 12 to $count, and 49.99 to $price. Print the gettype() output for each variable on its own line.

Show example solution
On each line write echo gettype(...) . "\n";.
Example solution:
<?php
$name = "Book";
$count = 12;
$price = 49.99;
echo gettype($name) . "\n";
echo gettype($count) . "\n";
echo gettype($price) . "\n";

Test yourself

  1. What does gettype(42) return?

    echo gettype(42);
    • "int"
    • "integer"
    • "number"
    • "42"
    Show answer

    "integer" — Correct! PHP returns "integer" for whole numbers.

  2. Print the type of $score

    echo ____($score);
    Show answer
    echo gettype($score);
  3. Match each value to its gettype output

    42
    integer
    3.14
    double
    "book"
    string
    null
    NULL

All lessons in Beginner