arrays

Arrays in PHP

Arrays in PHP

Arrays in PHP are used to store multiple values in a single variable. PHP supports both indexed arrays and associative arrays.

Indexed Arrays

An indexed array stores values with a numeric index:

      
        <?php
          $fruits = array("Apple", "Banana", "Cherry");
          echo $fruits[0]; // Outputs Apple
        ?>
      
    

Associative Arrays

Associative arrays use named keys to store values:

      
        <?php
          $person = array("name" => "John", "age" => 30);
          echo $person["name"]; // Outputs John
        ?>
      
    

Activity

Try It Yourself!

Create an associative array for a car with keys for "make", "model", and "year". Output the value of the "model" key.

Quiz

Quick Quiz

  1. What is the difference between an indexed array and an associative array?
  2. How do you access the value of an associative array?

Answers: Indexed arrays use numeric indexes, while associative arrays use named keys. Access values in associative arrays using the key (e.g., $array["key"]).