PHP Arrays

An array holds many values in one variable. PHP arrays are ordered maps — they work as both lists and dictionaries.

Indexed arrays

PHP
<?php
  $books = ["Muna Madan", "Palpasa Cafe", "Seto Dharti"];

  echo $books[0];        // Muna Madan  — indexes start at 0
  echo count($books);    // 3

  $books[] = "Karnali Blues";  // append
  $books[1] = "Radha";          // replace

The short [] syntax is preferred; older code uses array(...), which does the same thing.

Printing arrays

echo cannot print an array. Use:

PHP
<?php
  print_r($books);   // readable
  var_dump($books);  // readable + types

Multidimensional arrays

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

  echo $students[0]["name"];  // Sita

  foreach ($students as $s) {
      echo "{$s['name']}: {$s['marks']}<br>";
  }

Checking before you read

Reading a missing key emits a warning. Guard it:

PHP
<?php
  if (isset($books[5])) { echo $books[5]; }

  echo $books[5] ?? "not found";   // cleaner

  if (in_array("Radha", $books)) { echo "found"; }
  if (array_key_exists(0, $books)) { echo "index 0 exists"; }

isset() returns false for a key whose value is null; array_key_exists() returns true. That difference matters occasionally.

Removing elements

PHP
<?php
  unset($books[1]);          // removes the value, keeps other indexes
  $books = array_values($books); // renumber 0,1,2...

Forgetting array_values() after unset() leaves gaps in the numbering, which surprises for loops (though foreach handles it fine).