Course Content
About Lesson

Indexed and Associative Arrays

Arrays allow you to store multiple values in a single variable.

  • These are arrays with numeric indexes (0, 1, 2, …).
PHP
<?php
// Indexed Array
$fruits = array("Apple", "Banana", "Orange");

// Accessing elements
echo $fruits[0]; // Output: Apple
echo "<br>";
echo $fruits[1]; // Output: Banana
echo "<br>";
echo $fruits[2]; // Output: Orange
?>

Loop through Indexed Array (using for):

PHP
<?php
$fruits = array("Apple", "Banana", "Orange");
$length = count($fruits); // total elements

for ($i = 0; $i < $length; $i++) {
    echo $fruits[$i] . "<br>";
}
?>
    • These are arrays with named keys (like a dictionary).
    PHP
    <?php
    // Associative Array
    $student = array("name" => "John", "age" => 20, "grade" => "A");
    
    // Accessing elements
    echo "Name: " . $student["name"];
    echo "<br>";
    echo "Age: " . $student["age"];
    echo "<br>";
    echo "Grade: " . $student["grade"];
    ?>
    

    Loop through Associative Array (using foreach):

    PHP
    <?php
    $student = array("name" => "John", "age" => 20, "grade" => "A");
    
    foreach ($student as $key => $value) {
        echo $key . " : " . $value . "<br>";
    }
    ?>
    
      FeatureIndexed ArrayAssociative Array
      KeysNumbers (0,1,2,…)Strings (“name”,”age”,…)
      Example["Apple","Banana"]["name"=>"John","age"=>20]
      Accessing elements$arr[0]$arr["name"]