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.
Learn Python, JavaScript, Java and more with free interactive lessons, real projects and AI-powered help. Beginner-friendly.
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.
📋 Quick Reference — PHP Arrays
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.
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].