← PHP tutorial

PHP

Arrays

A regular (indexed) array is a numbered list: $fruits = ["apple", "banana"]. An associative array uses named keys instead of numbers.

Example: an associative array and foreach

<?php
  $student = ["name" => "Ada", "track" => "Frontend"];
  echo $student["name"] . " is studying " . $student["track"];

  foreach ($student as $key => $value) {
    echo "$key: $value\n";
  }
?>
Ada is studying Frontend
name: Ada
track: Frontend

=> pairs a key with its value when building an associative array. foreach ($student as $key => $value) steps through every key/value pair at once — for a plain indexed array, you'd instead write foreach ($fruits as $fruit), dropping the key since a numeric index usually isn't meaningful on its own.

Example
<?php
  $student = ["name" => "Ada", "track" => "Frontend"];
  echo $student["name"] . " is studying " . $student["track"];
?>
Output
Ada is studying Frontend