Arrays

Course 1 · Ch 6
Arrays: Indexed, Associative, and Common Array Functions
Storing collections of values — by position or by name — and the built-in functions for working with them

Arrays appeared briefly in Chapter 4's foreach examples. This chapter covers them properly: the two main styles PHP arrays come in, and the handful of built-in functions used constantly in real PHP code.

Indexed Arrays — Position-Based

<?php $fruits = ["apple", "banana", "cherry"]; echo $fruits[0]; // "apple" — indexing starts at 0, not 1 echo $fruits[2]; // "cherry" $fruits[] = "date"; // appends to the end — now index 3 print_r($fruits); // dumps the whole array readably ?>
PHP arrays are zero-indexed — the first element is index 0, not 1
This trips up plenty of beginners coming from everyday counting (where you'd naturally call "apple" the "first" item and expect it at position 1). $fruits[0] is the first element; $fruits[count($fruits) - 1] is the last.

Associative Arrays — Named Keys

<?php $person = [ "name" => "Philip", "age" => 35, "city" => "London" ]; echo $person["name"]; // "Philip" $person["email"] = "philip@example.com"; // adds a new key ?>

An associative array uses meaningful string keys instead of numeric positions — genuinely more readable than remembering "index 1 is always the age" when modelling real-world data like a person's details.

Multidimensional Arrays — Arrays of Arrays

<?php $people = [ ["name" => "Philip", "age" => 35], ["name" => "Sam", "age" => 28] ]; echo $people[0]["name"]; // "Philip" foreach ($people as $person) { echo $person["name"] . " is " . $person["age"] . "<br>"; } ?>

An array's elements can themselves be arrays — extremely common for representing lists of records, like rows that might later come from a database (covered in a future course on database integration).

Common Built-In Array Functions

FunctionWhat it does
count($arr)Number of elements
array_push($arr, $val)Adds to the end (same as $arr[] = $val)
array_pop($arr)Removes and returns the last element
array_merge($a, $b)Combines two arrays into one
in_array($val, $arr)Checks whether a value exists in the array
array_search($val, $arr)Returns the key/index of a value, or false if not found
sort($arr)Sorts values, re-indexes keys from 0
array_map($fn, $arr)Applies a function to every element, returns a new array
array_filter($fn, $arr)Keeps only elements where the function returns true
<?php $numbers = [1, 2, 3, 4, 5]; // array_map — transform every element $doubled = array_map(function($n) { return $n * 2; }, $numbers); print_r($doubled); // [2, 4, 6, 8, 10] // array_filter — keep only matching elements $evens = array_filter($numbers, function($n) { return $n % 2 == 0; }); print_r($evens); // [1 => 2, 3 => 4] — note original keys are preserved! ?>
array_map and array_filter take an anonymous function as an argument
The function($n) { ... } passed in is a function with no name, defined right where it's used — this pattern (a "callback") is genuinely common in PHP once you start using these array functions. It will feel more natural with practice; for now, treat it as "the rule to apply to each element," written inline rather than as a separately-named function.
array_filter preserves original keys — this surprises people expecting a clean 0,1,2... result
After filtering, the remaining elements keep whatever index/key they originally had, leaving gaps. If a clean re-indexed array is needed afterward, wrap the result in array_values().

Coding Challenges

Challenge 1

Create an associative array representing a book with keys "title", "author", and "year". Echo a formatted sentence using all three values, then add a new key "genre" and echo the whole array with print_r.

📄 View solution
Challenge 2

Given an indexed array of 6 numbers of your choice, use in_array() to check if 42 is present, array_search() to find the index of a number you know is in there, and sort() to put the array in ascending order. Echo the result of each step.

📄 View solution
Challenge 3

Given an array of 8 numbers, use array_filter() with an anonymous function to keep only numbers greater than 10, then use array_map() on the filtered result to square each remaining number. Wrap the filtered result in array_values() before mapping, and print_r the final array.

📄 View solution

Chapter 6 Quick Reference

  • Indexed arrays — zero-based numeric positions: $arr[0] is the first element
  • Associative arrays — named string keys: $arr["key"]
  • Multidimensional arrays — arrays of arrays, accessed like $arr[0]["key"]
  • count(), array_push/pop, array_merge, in_array, array_search, sort — everyday array operations
  • array_map($fn, $arr) — transforms every element, returns a new array
  • array_filter($fn, $arr) — keeps only matching elements, preserves original keys
  • array_values($arr) — re-indexes an array from 0, useful after filtering
  • Next chapter: strings — common string functions, formatting, and manipulation