PHP Data Types Explained: String, Integer, Float, Boolean, Array, Object, and NULL with Examples
When we create a variable in PHP, the type of data it can store defines how PHP treats that variable. Understanding data types is one of the most important foundations in programming.
In this lesson, we’ll learn all 7 primary data types used in PHP — each explained in detail with examples.
String
A String in PHP is a sequence of characters, like text enclosed in quotes.
Example:
<?php
$name = "John Doe";
echo "Welcome, $name!";
?>
Explanation:
Strings are written inside single (
' ') or double (" ") quotes.Double quotes allow variable interpolation (variables inside the string are evaluated).
Integer
An Integer represents a whole number — positive, negative, or zero — without decimals.
Example:
<?php
$age = 25;
echo "Age: $age";
?>
Key Points:
Integers can be written in decimal, octal, or hexadecimal form.
Range depends on the system (commonly -2,147,483,648 to 2,147,483,647 for 32-bit).
Float (or Double)
A Float (also called Double) stores numbers with decimals or fractions.
Example:
<?php
$price = 19.99;
echo "Product Price: $price";
?>
Use Case:
Used when you need precision with decimal numbers, like currency or measurements.
Boolean
A Boolean data type can hold only two values: TRUE or FALSE.
Example:
<?php
$is_logged_in = true;
if ($is_logged_in) {
echo "Welcome Back!";
}
?>
Usage:
Used in conditional statements and logic to control program flow.
Array
An Array holds multiple values in one variable.
It can be indexed, associative, or multidimensional.
Example (Associative Array):
<?php
$student = array("name" => "Alice", "age" => 20, "grade" => "A");
echo $student["name"];
?>
Explanation:
Arrays store data in key-value pairs.
Very useful for managing lists, records, or collections.
Object
An Object stores data and methods that operate on that data — used in Object-Oriented Programming (OOP).
Example:
<?php
class Car {
public $brand;
function setBrand($brand) {
$this->brand = $brand;
}
}
$myCar = new Car();
$myCar->setBrand("Toyota");
echo $myCar->brand;
?>
Explanation:
Objects represent real-world entities like a “Car,” “Student,” or “Product.”
NULL
NULL represents a variable with no value.
Example:
<?php
$value = null;
var_dump($value);
?>
Key Note:
A variable is
NULLif it has no value assigned.Useful for clearing or resetting variables.
Why Understanding Data Types Matters
Knowing how PHP stores and processes data helps you:
Write more efficient code
Prevent type conversion errors
Build scalable, error-free web applications
Practice Task
Create a PHP script that:
Declares one variable of each data type.
Uses
var_dump()to display the type and value.
Example Starter Code:
<?php
$string = "Hello";
$int = 10;
$float = 9.8;
$bool = true;
$array = [1, 2, 3];
class Demo {}
$obj = new Demo();
$nullVar = null;
var_dump($string, $int, $float, $bool, $array, $obj, $nullVar);
?>