PHP Data Types

Variables can store data of different types such as:

  • String ("Hello")
  • Integer (5)
  • Float (also called double) (1.0)
  • Boolean ( 1 or 0 )
  • Array ( array("I", "am", "an", "array") )
  • Object
  • NULL
  • Resource

Strings

A string is a sequence of characters. It can be any text inside quotes (single or double):

$x = "Hello!";
$y = 'Hello!';

Integers

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

Rules for integers:

  • Integers must have at least one digit
  • Integers must not have a decimal point
  • Integers can be either positive or negative

$x = 5;

Floats

A float, or floating point number, is a number with a decimal point.

$x = 5.01;

Booleans

A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.

$x = true;
$y = false;

Arrays

An array stores multiple values in one single variable.

$colors = array("Magenta", "Yellow", "Cyan");

NULL

Null is a special data type that can only have the value null. Variables can be declared with no value or emptied by setting the value to null. Also, if a variable is created without being assigned a value, it is automatically assigned null.

<?php
// Assign the value "Hello!" to greeting
$greeting = "Hello!";

// Empty the value greeting by setting it to null
$greeting = null;
?>

Classes and Objects

A class is a data structure useful for modeling things in the real world, and can contain properties and methods. Objects are instances a class, and are a convenient way to package values and functions specific to a class.

<?php
class Car {
    function Car() {
        $this->model = "Tesla";
    }
}

// create an object
$Lightning = new Car();

// show object properties
echo $Lightning->model;
?>

PHP Resource

A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions. You can use get_resource_type() function to see resource type.

<?php
// prints: mysql link
$c = mysql_connect();
echo get_resource_type($c) . "\n";

// prints: stream
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// prints: domxml document
$doc = new_xmldoc("1.0");
echo get_resource_type($doc->doc) . "\n";

php data types