phpPHP
Module 9: ArraysBeginner55 min read

PHP Ordered-Map Arrays, Copy-on-Write & Essential array_* Functions

Understand PHP arrays as hash-table ordered maps, Copy-on-Write memory semantics, destructuring, spread unpacking, and all core array_* functions.

Key Takeaways & Core Concepts
  • Functional: array_map, array_filter, array_reduce, array_walk.
  • Keys/Values/Columns: array_keys, array_values, array_column, array_flip, array_combine.
  • Search/Set/Slice: in_array($x, $arr, true) (always pass true for strict!), array_search, array_unique, array_merge, array_slice, array_splice, array_diff, array_intersect.

1. Internal Working: Ordered Hash Maps & Copy-on-Write

In PHP, every array is an ordered hash map supporting integer and string keys with O(1) average lookup. Assigning $b = $a; shares memory via Copy-on-Write (CoW) until either array is modified.

1. array_filter, array_map, array_reduce & array_column
1<?php
2$users = [
3 ["name" => "Aarav", "score" => 90],
4 ["name" => "Diya", "score" => 45],
5 ["name" => "Kabir", "score" => 80],
6];
7
8$passed = array_filter($users, fn($u) => $u["score"] >= 50);
9$names = array_column($passed, "name");
10$total = array_reduce($passed, fn($acc, $u) => $acc + $u["score"], 0);
11
12echo "Passed: " . implode(", ", $names) . " | Total: $total\n";
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: Combines `array_filter`, `array_column`, and `array_reduce` in a clean pipeline.

2. Modern Syntax: Destructuring & Spread (`...`)

  • [$first, $second] = [10, 20]; and ['id' => $id] = $row;
  • $merged = [...$a, ...$b]; (supports string keys since PHP 8.1!).

3. Essential Array Functions

  • Functional: array_map, array_filter, array_reduce, array_walk.
  • Keys/Values/Columns: array_keys, array_values, array_column, array_flip, array_combine.
  • Search/Set/Slice: in_array($x, $arr, true) (always pass true for strict!), array_search, array_unique, array_merge, array_slice, array_splice, array_diff, array_intersect.
Practice & AssessmentPHP Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)