Arrays
By the end of this lesson you'll store many values in one variable — ordered lists, key-value records, and nested tables — and reshape them at will with PHP's array functions, the everyday workhorse of real applications.
Part of the free Php course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1️⃣ Indexed Arrays — Ordered Lists
An array is a single variable that holds many values. The simplest kind is an indexed array — an ordered list where PHP labels each slot with a number starting at 0 , not 1. You create one with the modern short syntax [ ] (older code uses array(...) — same thing). You read a slot by its index, and you tack a value onto the end with the handy $array[] = ... shortcut, which lets PHP pick the next number for you.
2️⃣ Associative Arrays — Key → Value
When position isn't meaningful but a label is, use an associative array . Instead of numbers, you choose your own keys — usually strings — and pair each with a value using the => arrow (read it as "points to"). This is how PHP models a record: a user, a config setting, a row from a database. You look values up by key, and assigning to a new key adds it while assigning to an existing key overwrites it.
Notice the { $person['name'] } trick: inside a double-quoted string, wrapping an array lookup in curly braces lets PHP drop the value in cleanly. Without the braces, "$person['name']" confuses the parser.
3️⃣ Multidimensional Arrays & foreach
Because an array's values can themselves be arrays, you can build tables and nested structures — a list of records, a grid, JSON-shaped data. To walk through any array, reach for foreach : it hands you each element in turn without you tracking an index. To reach a nested value, stack the brackets: outer position, then inner key.
4️⃣ Adding & Removing Items
Arrays are not fixed in size — you grow and shrink them as the program runs. Append with the $a[] = shortcut or array_push (which can add several at once); add to the front with array_unshift . Remove and capture the last item with array_pop or the first with array_shift . To delete one specific element by key, use unset — but note it leaves a gap in the numbering rather than renumbering.
5️⃣ Transforming Data — map, filter, reduce
The real power of PHP arrays is its library of built-in functions. Three are worth learning by heart. array_map applies a function to every element and returns a new array. array_filter keeps only the elements your test returns true for. array_reduce boils the whole array down to a single value (a sum, a max, a joined string). Watch the argument order — array_map(fn, array) but array_filter(array, fn) . Alongside them, in_array , array_keys , array_values , and the string pair implode / explode cover most everyday needs.
Now you try. The script below is almost complete — fill in each ___ using the 👉 hint, then run it and check it against the Output panel.
6️⃣ Sorting, Merging & Unpacking
sort reorders an indexed list ascending — but it renumbers the keys , so on an associative array it would throw your labels away. For keyed data use asort (by value) or ksort (by key); for a custom rule use usort with a comparison function. To combine arrays, use array_merge or the newer spread operator ... ; and list() destructuring — written as [$x, $y] = [...] — unpacks an array straight into separate variables.
One more. Build a small contact card as an associative array, then loop it with foreach ($arr as $key => $value) , which hands you both halves of each pair.
Common Errors (and the fix)
- "Warning: Undefined array key 'email'" — you read a key that doesn't exist (a typo, or it was never set). PHP returns null and warns. Guard it with isset($a['email']) or supply a default with the null-coalescing operator: $a['email'] ?? 'none' .
- array_map and array_filter take their arguments in opposite orders — it's array_map(fn, $arr) but array_filter($arr, fn) . Swap them by mistake and you'll get a "TypeError: argument must be callable". When in doubt, the array comes second in map and first in filter/reduce.
- Your keys vanished after sorting an associative array — sort() (and rsort() ) reindex from 0, discarding string keys. To keep key→value pairs intact, use asort() / arsort() to sort by value, or ksort() to sort by key.
- "PHP Parse error: syntax error, unexpected '=>'" — you used the => arrow outside an array, or mixed it up with assignment = . The arrow only links a key to a value inside array brackets or a foreach .
Pro Tips
- 💡 Reach for map/filter/reduce before writing a loop. They state your intent ("transform", "keep", "total") and avoid off-by-one bugs from manual indexing.
- 💡 Use $a['key'] ?? $default whenever a key might be missing — it's the clean, warning-free way to read optional data.
- 💡 Pick one style per array. A purely indexed list or a purely associative record reads far clearer than one that mixes numeric and string keys.
📋 Quick Reference — PHP Arrays
Syntax / Function
Example
What It Does
[ ]
$a = [1, 2, 3];
Create an array (short syntax)
=>
["name" => "Al"]
Map a key to a value
$a[] =
$a[] = 4;
Append to the end
unset()
unset($a[1]);
Delete one key (no renumber)
count()
count($a)
Number of items
in_array()
in_array(2, $a)
Is a value present? (bool)
array_map()
array_map($fn, $a)
Transform every element
array_filter()
array_filter($a, $fn)
Keep matching elements
array_reduce()
array_reduce($a, $fn, 0)
Boil down to one value
sort() / usort()
usort($a, $cmp)
Reorder (renumbers keys)
asort() / ksort()
ksort($a)
Sort, keeping keys
array_merge()
array_merge($a, $b)
Combine arrays
implode() / explode()
implode(",", $a)
Array ↔ string
... / [ ] =
[...$a]; [$x] = $a;
Spread / list() unpack
Frequently Asked Questions
Mini-Challenge: Top Scorers
No code is filled in this time — just a brief and an outline. Write it yourself, run it on onecompiler.com/php or your own machine, then check your result against the expected output in the comments. This combines array_filter , usort , foreach and array_reduce — the real toolkit.
🎉 Lesson Complete!
- ✅ Indexed arrays are ordered lists keyed by numbers from 0 ; associative arrays map your own keys with =>
- ✅ Arrays nest: a multidimensional array holds arrays, and foreach walks any of them
- ✅ Grow and shrink with $a[] = , array_push/pop/shift/unshift , and unset
- ✅ array_map , array_filter , and array_reduce transform, keep, and combine data (mind the argument order)
- ✅ sort renumbers keys; use asort / ksort / usort to keep or customise order
- ✅ implode / explode , spread ... , and list() move data between arrays, strings, and variables
- ✅ Next lesson: File Handling — read and write files on the server
Practice quiz
What index does the first element of an indexed array have?
- 1
- -1
- 0
- It has no index
Answer: 0. Indexed arrays start numbering at 0, so the first item is $arr[0].
What does $fruits[] = "Date" do?
- Appends "Date" to the end of the array
- Deletes the last item
- Replaces index 0
- Throws an error
Answer: Appends "Date" to the end of the array. The $arr[] = ... shortcut appends a value, letting PHP pick the next index.
Which symbol maps a key to a value in an associative array?
- ->
- :
- ==
- =>
Answer: =>. The => arrow links a key to its value, e.g. ["name" => "Alice"].
What does count() return for an array?
- The largest value
- The number of items
- The last key
- The sum of values
Answer: The number of items. count() returns how many elements the array holds.
Which has the array argument FIRST: array_map or array_filter?
- array_filter
- array_map
- Both put it first
- Neither takes an array
Answer: array_filter. It's array_map(fn, array) but array_filter(array, fn) — the array comes first in filter.
What does array_reduce do?
- Removes duplicate items
- Sorts the array
- Boils the array down to a single value
- Reverses the array
Answer: Boils the array down to a single value. array_reduce combines all elements into one value, like a sum or a max.
What does in_array(8, $nums) return?
- The index of 8
- A boolean (true/false)
- The value 8
- The array length
Answer: A boolean (true/false). in_array returns a boolean indicating whether the value exists in the array.
What happens to keys after sort() runs on an array?
- Keys are kept as-is
- String keys are preserved
- It deletes all keys
- It renumbers keys from 0
Answer: It renumbers keys from 0. sort() reindexes from 0, discarding existing keys — so don't use it on associative arrays you want keyed.
What does unset($queue[1]) do to the remaining numeric keys?
- Renumbers them to fill the gap
- Removes index 1 but leaves a gap (no renumber)
- Deletes the whole array
- Sorts the array
Answer: Removes index 1 but leaves a gap (no renumber). unset deletes that one key but does not renumber the rest, leaving a gap.
What does [1, 2, 3, ...$more] do when $more is [4, 5]?
- Nests $more inside
- Causes a syntax error
The spread operator ... unpacks $more's elements into the new array: [1, 2, 3, 4, 5].
Continue this course
- Previous: Functions
- Next: File Handling