Skip to main content

PHP Data Types

PHP is a dynamic, server-side scripting language used mainly for web development. One of the fundamental concepts to grasp when learning PHP, or any programming language for that matter, is understanding data types. In PHP, we have 8 primitive data types that are used to construct our programs.

Understanding PHP Data Types

PHP data types are used to differentiate different types of data that can be used in PHP. The following are the 8 primitive data types:

  • Integer
  • Double (floating-point numbers)
  • String
  • Boolean
  • Array
  • Object
  • NULL
  • Resource

Let's go over each of these data types one by one.

Integer

An integer is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A variable is considered integer if it has no decimal point and no exponential part.

<?php
$a = 1234; // decimal number
$b = -123; // a negative number
$c = 0x1A; // hexadecimal number
$d = 0123; // octal number
?>

Double

Double is a number with a decimal point or a form of scientific notation. In PHP, both float and double data types are used to represent floating point numbers.

<?php
$a = 1.234;
$b = 10.2e3;
$c = 4E-10;
?>

String

A string is a sequence of characters. In PHP, 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;
?>

Boolean

A Boolean represents two possible states: TRUE or FALSE.

<?php
$x = true;
$y = false;
?>

Array

An array stores multiple values in one single variable.

<?php
$cars = array("Volvo","BMW","Toyota");
echo "I like " . $cars[0];
?>

Object

In PHP, an object must be explicitly declared. First, we must declare a class of object. For this, we use the class keyword. A class is a structure that contains properties and methods.

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

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

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

NULL

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;
var_dump($x);
?>

Resource

Resource is a special data type in PHP. It is not an actual data type, but it is used to store references to functions and resources external to PHP.

A common example of using the resource data type is a database call.

<?php
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
var_dump($conn);
?>

In this tutorial, we covered PHP's 8 primitive data types. Understanding these data types and when to use them is crucial when learning PHP. Happy coding!