About Lesson
Indexed and Associative Arrays
Arrays allow you to store multiple values in a single variable.
1. Indexed Arrays:
- These are arrays with numeric indexes (0, 1, 2, …).
Example:
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>";
}
?>
2. Associative Arrays:
- These are arrays with named keys (like a dictionary).
Example:
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>";
}
?>
Key Difference Between Indexed and Associative Arrays:
Feature | Indexed Array | Associative Array |
---|---|---|
Keys | Numbers (0,1,2,…) | Strings (“name”,”age”,…) |
Example | ["Apple","Banana"] | ["name"=>"John","age"=>20] |
Accessing elements | $arr[0] | $arr["name"] |