PHP Associative Arrays

An associative array uses named keys instead of numeric indexes — PHP's equivalent of a dictionary or hash map.

PHP
<?php
  $student = [
      "name"    => "Sita Karki",
      "roll"    => 12,
      "faculty" => "Science",
  ];

  echo $student["name"];   // Sita Karki
  $student["grade"] = "A"; // add a new key

Looping with keys

PHP
<?php
  foreach ($student as $key => $value) {
      echo "$key: $value<br>";
  }

Useful key/value functions

PHP
<?php
  print_r(array_keys($student));    // ["name", "roll", "faculty"]
  print_r(array_values($student));  // ["Sita Karki", 12, "Science"]

  var_dump(array_key_exists("roll", $student)); // true
  var_dump(in_array("Science", $student));      // true (searches values)

Merging

PHP
<?php
  $defaults = ["limit" => 10, "sort" => "name"];
  $options  = ["limit" => 25];

  $config = array_merge($defaults, $options);
  // ["limit" => 25, "sort" => "name"]  — later wins

  $config = [...$defaults, ...$options]; // same, PHP 8.1+ spread

Careful: array_merge() renumbers integer keys. To preserve them, use the + operator instead — but note + keeps the left side on conflict, the opposite of array_merge():

PHP
<?php
  $a = [1 => "one"];
  $b = [1 => "uno"];

  print_r(array_merge($a, $b)); // [0 => "one", 1 => "uno"]
  print_r($a + $b);              // [1 => "one"]

Sorting associative arrays

PHP
<?php
  $marks = ["Sita" => 88, "Ram" => 74, "Hari" => 91];

  asort($marks);   // by value, ascending, keys preserved
  arsort($marks);  // by value, descending
  ksort($marks);   // by key, ascending
  krsort($marks);  // by key, descending

Use sort()/rsort() only on indexed arrays — they discard keys.