← 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
Ready to go further?

These free tutorials are a preview, our Backend Development cohort covers it in depth, with a real project and a cohort alongside you. Active

Enroll in Backend Development
Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account