Back to Curriculum

Arrays and Array Functions

📚 Lesson 5 of 12 ⏱️ 40 min

Arrays and Array Functions

40 min

PHP arrays are powerful, flexible data structures that can function as arrays, lists, hash tables, dictionaries, and more. Unlike many languages that have separate array and hash table types, PHP uses a single array type for both indexed and associative arrays. Arrays can have numeric keys (indexed arrays), string keys (associative arrays), or both. This flexibility makes PHP arrays versatile but requires understanding their behavior to use them effectively.

PHP provides extensive built-in array functions for common operations. Functions like `array_map()` (transform elements), `array_filter()` (filter elements), `array_reduce()` (aggregate values), `array_merge()` (combine arrays), `array_slice()` (extract portions), and many more enable powerful array manipulation. Understanding these functions helps you write concise, efficient array processing code. Many array functions accept closures or arrow functions for custom logic.

Array destructuring (PHP 7.1+) allows you to assign array elements to variables in a single statement. This is more concise than accessing elements individually. The spread operator (`...`) (PHP 7.4+) enables merging arrays, unpacking arrays into function arguments, and creating new arrays from existing ones. These modern features make array manipulation more elegant and readable.

Array iteration is typically done with `foreach`, which is the most efficient and readable way to process arrays. `foreach` can iterate over values only or both keys and values. For indexed arrays, you can also use traditional `for` loops, but `foreach` is generally preferred. Understanding array iteration helps you process array data effectively.

Array functions enable powerful data transformations. `array_map()` applies a function to each element, `array_filter()` selects elements matching criteria, `array_reduce()` aggregates values, `array_search()` finds elements, `array_keys()`/`array_values()` extract keys/values, and many more. These functions enable functional programming patterns in PHP. Understanding array functions helps you write expressive, efficient array processing code.

Best practices include using `foreach` for iteration, leveraging array functions for transformations, using array destructuring when appropriate, understanding array key types (numeric vs string), and being aware of array reference behavior. Arrays are fundamental to PHP programming, and mastering them enables you to handle data effectively. Understanding arrays and array functions is essential for productive PHP development.

Key Concepts

  • PHP arrays can be indexed, associative, or mixed.
  • Array functions (map, filter, reduce) enable powerful transformations.
  • Array destructuring assigns array elements to variables concisely.
  • The spread operator (...) merges arrays and unpacks arguments.
  • foreach is the preferred way to iterate over arrays.

Learning Objectives

Master

  • Working with indexed and associative arrays
  • Using array functions for data transformation
  • Understanding array destructuring and spread operator
  • Iterating over arrays effectively with foreach

Develop

  • Data manipulation and transformation thinking
  • Understanding functional programming patterns with arrays
  • Designing efficient array processing code

Tips

  • Use foreach for array iteration—it's most readable and efficient.
  • Leverage array functions (map, filter, reduce) for transformations.
  • Use array destructuring for concise variable assignment.
  • Use the spread operator for merging arrays and function arguments.

Common Pitfalls

  • Using for loops with array indices when foreach would be simpler.
  • Not understanding array key types, causing unexpected behavior.
  • Modifying arrays during iteration, causing unexpected results.
  • Not using array functions, writing verbose manual loops.

Summary

  • PHP arrays are flexible data structures for indexed and associative data.
  • Array functions enable powerful data transformations.
  • Array destructuring and spread operator provide modern array features.
  • foreach is the preferred way to iterate over arrays.
  • Understanding arrays is fundamental to PHP programming.

Exercise

Demonstrate various array operations and built-in array functions.

<?php
// Indexed array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Associative array
$students = [
    ["name" => "Alice", "grade" => 85],
    ["name" => "Bob", "grade" => 92],
    ["name" => "Charlie", "grade" => 78],
    ["name" => "Diana", "grade" => 95]
];

echo "<h3>Array Functions:</h3>";

// Count elements
echo "Count: " . count($numbers) . "<br>";

// Filter even numbers
$evenNumbers = array_filter($numbers, fn($n) => $n % 2 == 0);
echo "Even numbers: " . implode(", ", $evenNumbers) . "<br>";

// Map to squares
$squares = array_map(fn($n) => $n * $n, $numbers);
echo "Squares: " . implode(", ", $squares) . "<br>";

// Reduce to sum
$sum = array_reduce($numbers, fn($carry, $item) => $carry + $item, 0);
echo "Sum: " . $sum . "<br>";

// Sort students by grade
usort($students, fn($a, $b) => $b["grade"] - $a["grade"]);
echo "<h3>Students sorted by grade:</h3>";
foreach ($students as $student) {
    echo $student["name"] . ": " . $student["grade"] . "<br>";
}

// Array destructuring
[$first, $second, $third] = $numbers;
echo "First three: $first, $second, $third<br>";

// Merge arrays
$array1 = [1, 2, 3];
$array2 = [4, 5, 6];
$merged = [...$array1, ...$array2];
echo "Merged: " . implode(", ", $merged) . "<br>";
?>

Code Editor

Output