A PHP array is an ordered map that associates keys with values and can work as a list or dictionary.
In real web development, you almost never work with isolated data. You work with lists of products, collections of users, or rows from a database. For all of this, we use Arrays.
The short syntax [] is the standard way to declare arrays. The array() syntax is still valid, but it’s less common in modern code.
Indexed arrays (lists)
These are the classic arrays. A list of elements where each one has a numeric position (index), always starting at 0.
// Definition
$technologies = ['PHP', 'Laravel', 'Docker', 'React'];
// Access
echo $technologies[0]; // Output: PHP
echo $technologies[2]; // Output: Docker
// Add an element to the end
$technologies[] = 'Linux';PHP automatically assigns the numbers:
- 0 => ‘PHP’
- 1 => ‘Laravel’
- …
When to use them? When order matters and the elements are of the same type (e.g., a list of prices, a list of names).
Associative arrays (dictionaries / maps)
This is where PHP shines. Instead of using automatic numbers to access data, you define Keys with meaningful names.
It’s the equivalent of a JSON Object or a Python Dictionary.
$product = [
'name' => '4K Monitor',
'price' => 299.99,
'stock' => true,
'brand' => 'Dell'
];
// Access (much more readable)
echo "The product {$product['name']} costs {$product['price']}€";Notice the arrow =>. It means “This key points to this value”.
When to use them? When you want to describe an entity with properties (a user, a product, a configuration).
Multidimensional arrays (inception)
An array can contain… other arrays! This allows handling more complex data structures.
Imagine a list of users (Indexed) where each user has their data (Associative).
$users = [
[
'name' => 'Luis',
'role' => 'Admin'
],
[
'name' => 'Ana',
'role' => 'Editor'
]
];
// Access the name of the second user
echo $users[1]['name']; // Output: AnaModern manipulation (spread operator ...)
Since PHP 7.4 we can unpack arrays with numeric keys using ...; PHP 8.1 added support for string keys. It’s a convenient alternative to array_merge in many cases.
$fruits = ['Apple', 'Pear'];
$vegetables = ['Lettuce', 'Tomato'];
// Merge into a new one
$basket = [...$fruits, ...$vegetables, 'Bread'];
// Result: ['Apple', 'Pear', 'Lettuce', 'Tomato', 'Bread']It’s fast, visual, and very powerful.
How can I see what’s inside? (debugging)
If you try echo $array, PHP will yell at you (or just print the word “Array”).
To see the content of an array while developing, we use:
print_r($array): Shows a basic structure.var_dump($array): Shows structure + data types + length (The most complete).
If you see the result in the browser and it looks all bunched up and ugly, wrap it in <pre> tags:
echo "<pre>";
var_dump($users);
echo "</pre>";This formats the output to be readable.