In PHP, an array is a special, highly versatile variable type that can hold more than one value at a time. Instead of creating separate variables for related pieces of data, you can group them together inside a single array.
Tip: If you are used to other programming languages, you may be familiar with the difference between a zero-indexed Array and a key-value Map, in PHP these are combined into the single array type and its behaviour depends on how you use it.
Indexed arrays store multiple values in a numbered list. By default, PHP assigns a numeric index to each item, starting at 0 for the first item, 1 for the second, and so on.
You can create an array using the modern short array syntax [] (recommended) or the older array() function.
<?php
// Creating an indexed array
$fruits = ["Apple", "Banana", "Orange"];
// Accessing array elements using their index
echo $fruits[0]; // Outputs: Apple
echo $fruits[2]; // Outputs: Orange
Associative arrays are incredibly powerful because they allow you to use named keys (strings) that you assign to values, rather than relying on strict numeric order. This makes your data much easier to read and access.
You associate a key with a value using the => (double arrow) operator.
<?php
$user = [
"name" => "Alice",
"email" => "alice@example.com",
"role" => "Admin"
];
// Accessing data via named keys
echo $user["name"]; // Outputs: Alice
echo $user["role"]; // Outputs: Admin
Adding and Modifying Elements Arrays in PHP are completely dynamic. You can easily add new items or change existing ones after the array has been created.
If you provide empty square brackets [] when assigning a value, PHP will automatically append the new value to the end of the array.
<?php
$colors = ["Red", "Green"];
// Appending a new element
$colors[] = "Blue";
// Modifying an existing element
$colors[0] = "Dark Red";
// Adding a new key to an associative array
$user["age"] = 28;
Because an array can hold any type of data, it can even hold other arrays. These are called multidimensional arrays and are often used to store tabular data, like rows retrieved from a database.
<?php
$users = [
[
"name" => "Alice",
"role" => "Admin"
],
[
"name" => "Bob",
"role" => "Editor"
]
];
// Accessing Bob's role (Index 1 is the second array)
echo $users[1]["role"]; // Outputs: Editor