How to Create and Use Arrays in PHP
Arrays are one of the most powerful data structures in PHP, allowing you to store multiple values in a single variable. Whether you’re building a simple list or a complex data model, mastering arrays is essential for every PHP developer.
Table of Contents
- What Is an Array in PHP?
- Creating Indexed Arrays
- Creating Associative Arrays
- Creating Multidimensional Arrays
- Common Array Functions
- Looping Through Arrays
- Best Practices & Tips
What Is an Array in PHP?
An array in PHP is a special variable that can hold more than one value at a time. PHP arrays are ordered maps, meaning they can use both integer and string keys. This flexibility makes them suitable for:
- Storing lists of items (indexed arrays)
- Mapping names to values (associative arrays)
- Representing tables, matrices, or JSON‑like structures (multidimensional arrays)
Creating Indexed Arrays
Indexed arrays use numeric keys that start at 0 by default. There are three common ways to create them:
1. Using the array() construct
$colors = array('red', 'green', 'blue');
echo $colors[1]; // outputs: green
2. Using short array syntax (PHP 5.4+)
$fruits = ['apple', 'banana', 'cherry'];
echo $fruits[2]; // outputs: cherry
3. Adding elements dynamically
$numbers = [];
$numbers[] = 10; // key 0
$numbers[] = 20; // key 1
$numbers[5] = 30; // explicit key 5
Creating Associative Arrays
Associative arrays let you use meaningful string keys instead of numeric indexes.
Basic syntax
$person = [
'first_name' => 'John',
'last_name' => 'Doe',
'age' => 28
];
echo $person['first_name']; // outputs: John
Mixing numeric and string keys
$mixed = [
0 => 'zero',
'one' => 1,
2 => 'two',
'three' => 3
];
Creating Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays. They are perfect for representing tables, matrices, or JSON objects.
Example: A simple matrix
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // outputs: 6
Example: A list of users
$users = [
[
'id' => 1,
'name' => 'Alice',
'email' => 'alice@example.com'
],
[
'id' => 2,
'name' => 'Bob',
'email' => 'bob@example.com'
]
];
echo $users[0]['email']; // outputs: alice@example.com
Common Array Functions in PHP
PHP ships with a rich set of built‑in functions that make working with arrays fast and expressive.
Counting Elements
$count = count($fruits); // returns 3
Adding & Removing Items
// Push to the end
array_push($fruits, 'date');
// Pop from the end
$last = array_pop($fruits);
// Unshift (add to beginning)
array_unshift($fruits, 'elderberry');
// Shift (remove from beginning)
$first = array_shift($fruits);
Merging Arrays
$all = array_merge($colors, $fruits);
Searching
$index = array_search('banana', $fruits); // returns the numeric key
$exists = in_array('green', $colors); // true or false
Sorting
sort($numbers); // ascending, reindexes keys
rsort($numbers); // descending
asort($person); // sort by value, preserve keys
ksort($person); // sort by key
Looping Through Arrays
Iterating over arrays is a daily task. The most common loop is foreach, but for and while can also be useful.
Using foreach
// Indexed array
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n";
}
// Associative array
foreach ($person as $key => $value) {
echo "$key => $value\n";
}
Using for with numeric indexes
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i] . PHP_EOL;
}
Iterating a multidimensional array
foreach ($users as $user) {
echo $user['name'] . ' (' . $user['email'] . ')' . PHP_EOL;
}
Best Practices & Tips
- Use short array syntax (
[]) for cleaner code. - Prefer
foreachfor readability and automatic key handling. - Never mix data types within the same array unless it’s intentional; it can lead to subtle bugs.
- Validate keys when using associative arrays to avoid undefined index notices.
- Leverage built‑in functions instead of writing custom loops; they’re usually faster and more reliable.
- Document complex structures with comments or type‑hinting (PHP 7.4+ supports typed properties).
Conclusion
Arrays are the backbone of data handling in PHP. By mastering indexed, associative, and multidimensional arrays, along with the powerful suite of array functions, you’ll be equipped to build robust applications, manipulate data efficiently, and write cleaner, more maintainable code.
Ready to put your new skills into practice? Start coding, experiment with the examples above, and explore PHP’s extensive array reference for deeper insights.