ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 8 min read

Indexed, Associative & Multidimensional Arrays

Mastering PHP dictionary mappings and array transformation pipelines

An array in PHP is actually an ordered map—a data type that associates values to keys. This allows PHP arrays to function as lists, hash maps, queues, and multidimensional matrices seamlessly.

Working with Arrays in PHP

Indexed arrays use numeric indices starting at 0: $colors = ["red", "green", "blue"];.

Associative arrays use named keys: $user = ["name" => "Sarah", "role" => "Admin"];.

The foreach loop provides clean iteration over both keys and values: foreach ($map as $key => $val).

PHP includes hundreds of built-in array functions such as array_map(), array_filter(), array_merge(), and in_array().

Associative Array and Transformation
<?php
  $products = [
    ["id" => 101, "name" => "Mechanical Keyboard", "price" => 129.99, "stock" => 14],
    ["id" => 102, "name" => "Ergonomic Mouse", "price" => 59.99, "stock" => 0],
    ["id" => 103, "name" => "4K Monitor 27\"", "price" => 349.00, "stock" => 8],
  ];

  // Filter in-stock items
  $inStock = array_filter($products, function($p) {
    return $p["stock"] > 0;
  });

  // Calculate total inventory value
  $totalVal = array_reduce($inStock, function($acc, $p) {
    return $acc + ($p["price"] * $p["stock"]);
  }, 0);

  echo "Available inventory value: $" . number_format($totalVal, 2);
?>
array_filter and array_reduce provide declarative, functional array manipulation in PHP.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which syntax defines an associative array pairing in PHP?