Arrays (Indexed & Associative)

🐘 PHP Lesson 6 Beginner

PHP arrays are highly flexible collections. They act as both indexed arrays and key-value associative arrays.

1 Indexed vs. Associative arrays

PHP defines arrays using two structures:

  • Indexed Array: Accessed using numeric indexes: `$fruits = ["Apple", "Banana"];`.
  • Associative Array: Accessed using named keys, acting like hash maps: `$user = ["name" => "Bob", "age" => 22];`.
2 Array Operations

Let's run a program declaring indexed and associative arrays, adding items dynamically, and iterating over their keys:

PHP — Arrays ▶ Run Code
<?php
// Indexed Array
$colors = ["Red", "Green", "Blue"];
$colors[] = "Yellow"; // Add element dynamically at end index

// Associative Array
$student = [
    "name" => "Alice",
    "gpa" => 3.8
];

echo "Second Color: " . $colors[1] . "\n";

echo "Iterating Associative student keys:\n";
foreach ($student as $key => $value) {
    echo $key . ": " . $value . "\n";
}
?>
3 Code Challenge
Challenge: Write a program that declares an associative array mapping product names to prices. Write a foreach loop to print each product and its price.