PHP Arrays
What Is an Array?
In simple terms: An array is a single variable that holds many values. Instead of creating $student1, $student2, $student3, … you store all students in one array and work with them as a group. Technically: A PHP array is an ordered map: a collection of key → value pairs that remembers the order in which elements were added. Keys are integers or strings; values can be of any type, including other arrays. The same structure serves as a list, a dictionary, a stack, a queue, or a table of records.
Why Arrays Are Essential
Without arrays:
$product1 = 'Keyboard';
$product2 = 'Mouse';
$product3 = 'Monitor';
// How many products are there? How do you loop over them?
With an array:
<?php
$products = ['Keyboard', 'Mouse', 'Monitor'];
echo count($products) . " products\n";
foreach ($products as $product) {
echo "- $product\n";
}
Output
3 products
- Keyboard
- Mouse
- Monitor
Arrays make it possible to count, loop over, search, sort, filter, and transform collections of any size. Database results, form submissions, configuration, and decoded JSON all arrive in PHP as arrays.
Creating Arrays
Short Syntax (Recommended)
$colors = ['red', 'green', 'blue'];
$user = ['name' => 'Asha', 'age' => 24];
$empty = [];
Long Syntax
$colors = array('red', 'green', 'blue');
Both create identical arrays. The short [] syntax (available since PHP 5.4) is the modern standard; you will see array() in older code.
Keys and Values
Every element has a key and a value:
<?php
$product = [
'name' => 'Desk Lamp',
'price' => 1299.0,
'tags' => ['home', 'lighting'],
'inStock' => true,
];
var_dump($product);
Output
array(4) {
["name"]=>
string(9) "Desk Lamp"
["price"]=>
float(1299)
["tags"]=>
array(2) {
[0]=>
string(4) "home"
[1]=>
string(8) "lighting"
}
["inStock"]=>
bool(true)
}
What This Shows
array(4)— the array has four elements.["name"]=>— a string key.- Values have different types: string, float, array, and boolean.
tagscontains a nested array with integer keys0and1.var_dump()shows types and lengths;print_r()shows a shorter, human-friendly view. Both are debugging tools.
The Three Common Kinds of Arrays
PHP has only one array type, but it is commonly used in three ways:
| Kind | Keys | Example | Typical Use | Lesson |
|---|---|---|---|---|
| Indexed | 0, 1, 2, … (automatic) | ['Mango', 'Banana'] | Lists | Indexed Arrays |
| Associative | Meaningful strings | ['name' => 'Asha', 'city' => 'Chennai'] | Records, settings, lookups | Associative Arrays |
| Multidimensional | Arrays inside arrays | [['id' => 1, 'name' => 'Asha'], ...] | Tables, nested data | Multidimensional Arrays |
<?php
$fruits = ['Mango', 'Banana', 'Guava']; // indexed
$user = ['name' => 'Asha', 'city' => 'Chennai']; // associative
$orders = [ // multidimensional
['id' => 101, 'total' => 1250],
['id' => 102, 'total' => 640],
];
echo $fruits[0] . "\n";
echo $user['city'] . "\n";
echo $orders[1]['total'] . "\n";
Output
Mango
Chennai
640
- Indexed arrays are accessed by position, starting at
0. - Associative arrays are accessed by name.
- Multidimensional arrays use one bracket per level:
$orders[1]['total']is "thetotalof the second order".
Basic Operations
<?php
$cart = ['Pen', 'Notebook'];
$cart[] = 'Eraser'; // add to the end
$cart[0] = 'Gel Pen'; // update an element
unset($cart[1]); // remove an element
echo count($cart) . " items\n";
print_r($cart);
var_dump(in_array('Eraser', $cart, true));
Output
2 items
Array
(
[0] => Gel Pen
[2] => Eraser
)
bool(true)
| Operation | Syntax | Lesson |
|---|---|---|
| Read an element | $array[$key] | Access Array Items |
| Update an element | $array[$key] = $value; | Update Array Items |
| Add to the end | $array[] = $value; | Add Array Items |
| Remove an element | unset($array[$key]); | Remove Array Items |
| Count elements | count($array) | Array Functions |
| Check for a value | in_array($value, $array, true) | Search in Arrays |
Notice that unset() removed key 1 but did not renumber the remaining keys — Eraser still has key 2. This is explained in Remove Array Items.
Arrays Are Ordered Maps
PHP arrays keep elements in insertion order, regardless of key type, and can mix integer and string keys:
<?php
$data = [5 => 'five', 'x' => 'ex', 1 => 'one'];
$data[] = 'next';
print_r($data);
Output
Array
(
[5] => five
[x] => ex
[1] => one
[6] => next
)
- Elements appear in the order they were added, not sorted by key.
$data[] = ...uses the largest integer key so far plus one (5 + 1 = 6).- Keys can only be integers or strings. Other key types are converted — for example,
"8"becomes8andtruebecomes1(see PHP Type Juggling).
Arrays Are Copied on Assignment
Arrays are values, not references. Assigning an array to another variable creates an independent copy:
<?php
$original = ['red', 'green'];
$copy = $original;
$copy[] = 'blue';
echo count($original) . " / " . count($copy) . "\n";
Output
2 / 3
The same applies when passing an array to a function. PHP uses copy-on-write, so the actual copying happens only if one of the arrays is modified — passing large arrays around is cheap.
Looping Over Arrays
foreach is the standard way to process every element:
<?php
$stock = ['Keyboard' => 12, 'Mouse' => 0, 'Monitor' => 4];
foreach ($stock as $product => $quantity) {
echo "$product: $quantity\n";
}
Output
Keyboard: 12
Mouse: 0
Monitor: 4
See Foreach Loop for details, including modifying arrays during a loop.
Built-in Array Functions
PHP provides around 80 array functions. The most important groups:
| Purpose | Examples | Lesson |
|---|---|---|
| Counting and checking | count(), array_key_exists(), in_array(), array_is_list() | Search in Arrays |
| Adding and removing | array_push(), array_pop(), array_shift(), array_unshift(), array_splice() | Add / Remove Array Items |
| Sorting | sort(), rsort(), asort(), ksort(), usort() | Sorting Arrays |
| Combining | array_merge(), array_combine(), + | Merge Arrays |
| Transforming | array_map(), array_filter(), array_reduce() | array_map / array_filter / array_reduce |
| Extracting | array_keys(), array_values(), array_column(), array_slice() | Array Functions |
| Calculating | array_sum(), array_product(), max(), min() | Array Functions |
Arrays and JSON
APIs exchange data as JSON, which maps naturally onto PHP arrays:
<?php
$product = ['id' => 7, 'name' => 'Desk Lamp', 'tags' => ['home', 'lighting']];
$json = json_encode($product);
echo $json . "\n";
$decoded = json_decode($json, true);
echo $decoded['tags'][1] . "\n";
Output
{"id":7,"name":"Desk Lamp","tags":["home","lighting"]}
lighting
- Associative arrays become JSON objects (
{...}); lists become JSON arrays ([...]). json_decode($json, true)converts JSON back into associative arrays. Withouttrue, JSON objects becomestdClassobjects.
Practical Example: A Simple Gradebook
<?php
$scores = ['Asha' => 88, 'Bala' => 72, 'Charu' => 95, 'Dev' => 64];
$passMark = 70;
$average = array_sum($scores) / count($scores);
$topScore = max($scores);
$topStudent = array_search($topScore, $scores, true);
$passed = array_filter($scores, fn(int $score): bool => $score >= $passMark);
arsort($scores);
echo "Average: $average\n";
echo "Top student: $topStudent ($topScore)\n";
echo "Passed: " . count($passed) . " of " . count($scores) . "\n";
echo "Ranking:\n";
$rank = 1;
foreach ($scores as $name => $score) {
echo " $rank. $name — $score\n";
$rank++;
}
Output
Average: 79.75
Top student: Charu (95)
Passed: 3 of 4
Ranking:
1. Charu — 95
2. Asha — 88
3. Bala — 72
4. Dev — 64
Step-by-Step Explanation
- The associative array maps each student's name to a score.
array_sum()andcount()give the average: 319 / 4 = 79.75.max()finds the highest score, andarray_search()finds the key (student name) with that value.array_filter()keeps only passing scores.arsort()sorts by score in descending order while keeping the names as keys.- The loop prints the ranking with a counter. Each of these functions is explained in the lessons of this section.
Common Mistakes
Reading a Key That Does Not Exist
Effect: Warning: Undefined array key. Fix: Check with isset() or use a default: $user['phone'] ?? 'not provided'.
Expecting unset() to Renumber Keys
Effect: Gaps in indexed arrays, and for loops that read missing keys. Fix: Use foreach, or re-index with array_values().
Using + to Append Lists
Effect: [1, 2] + [3, 4, 5] gives [1, 2, 5], because + keeps existing keys. Fix: Use array_merge() or [...$a, ...$b].
Echoing an Array
Effect: Prints Array with an "Array to string conversion" warning. Fix: Use implode(), a loop, print_r(), or json_encode().
Loose Searching
Effect: in_array('1e1', ['10']) is true. Fix: Pass true as the third argument for strict comparison.
Best Practices
- Use the short
[]syntax. - Use indexed arrays for lists and associative arrays for records and lookups.
- Use
foreachto loop over arrays. - Use strict comparisons in search functions.
- Prefer built-in array functions to hand-written loops for common tasks.
- For complex records used throughout an application, consider classes with typed properties instead of large associative arrays. Official reference: https://www.php.net/manual/en/language.types.array.php