Variables can store data of different types, and different data types can do different things. PHP supports several data types that allow you to work with text, numbers, logic, and complex collections of data.
Before we dive into types, you must know about var_dump(). It is a built-in PHP function that returns the data type and value of a variable. It is the most useful tool for debugging and learning data types.
<?php
$x = 5;
var_dump($x); // Outputs: int(5)
?>
PHP supports the following primary data types:
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!';
?>
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647. An integer must have at least one digit and cannot contain commas or blanks.
<?php
$x = 5985;
var_dump($x);
?>
A float (floating point number) is a number with a decimal point or a number in exponential form. In some documentation, it is also referred to as a double.
<?php
$x = 10.365;
var_dump($x);
?>
A Boolean represents two possible states: TRUE or FALSE. Booleans are often used in conditional testing.
<?php
$x = true;
$y = false;
?>
An array stores multiple values in one single variable. It is a collection of data, and can store values of different types within the same array.
<?php
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
?>
Classes and objects are the two main aspects of object-oriented programming. An object is a data type which stores data and information on how to process that data with methods.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
}
$myCar = new Car("black", "Volvo");
var_dump($myCar);
?>
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.
<?php
$x = "Hello world!";
$x = null; // $x is now NULL
var_dump($x);
?>