Data Types

Variables can store data of different types, and different data types can do different things.

PHP supports the following data types:

  • String
  • Integer
  • Float (floating point numbers - also called double)
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

String :

A string is a sequence of characters, like "Hello world!".

A string can be any text inside quotes. You can use single or double quotes:

    
        <?php
            $x = "Hello world!";
            $y = 'Hello world!';

            echo $x;
            echo "<br>";
            echo $y;
        ?>
    

Integer :

An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.


Rules for integers :

  • An integer must have at least one digit
  • An integer must not have a decimal point
  • An integer can be either positive or negative
  • Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation

    
        <?php
            $x = 123;
            echo $x;
        ?>
    

Float :

A float (floating point number) is a number with a decimal point or a number in exponential form.

    
        <?php
            $x = 123.45;
            echo $x;
        ?>
    

Boolean :

A Boolean represents two possible states: TRUE or FALSE.

    
        $x = true;
        $y = false;
    

Here are the rules for determine the "truth" of any value not already of the Boolean type:


  • If the value is a number, it is false if exactly equal to zero and true otherwise.
  • If the value is a string, it is false if the string is empty (has zero characters) or is the string "0", and is true otherwise.
  • Values of type NULL are always false.
  • If the value is an array, it is false if it contains no other values, and it is true otherwise. For an object, containing a value means having a member variable that has been assigned a value.
  • Valid resources are true (although some functions that return resources when they are successful will return FALSE when unsuccessful).
  • Don't use double as Booleans.

NULL Value

Null is a special data type which can have only one value: NULL.

A variable of data type NULL is a variable that has no value assigned to it.

    
        $my_var = null;
    

A variable that has been assigned NULL has the following properties:

  • It evaluates to FALSE in a Boolean context.
  • It returns FALSE when tested with IsSet() function.

The escape-sequence replacements are:

  • \n is replaced by the newline character
  • \r is replaced by the carriage-return character
  • \t is replaced by the tab character
  • \$ is replaced by the dollar sign itself ($)
  • \" is replaced by a single double-quote (")
  • \\ is replaced by a single backslash (\)