📦 Lesson 5: Arrays in PHP

  Arrays in PHP


An array is a special variable that allows you to store multiple values in a single variable. Think of it as a container that holds a group of related items.

🧾 Why Use Arrays?

  • To group related data under one variable
  • To loop through multiple values
  • To store and organize structured data

🔢 1. Indexed Arrays

Indexed arrays use numbers as keys (starting from 0).

$fruits = ["apple", "banana", "orange"];

echo $fruits[0]; // apple
echo $fruits[1]; // banana
  

Loop Example:

foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}
  

🗂️ 2. Associative Arrays

Associative arrays use named keys instead of numeric indexes.

$person = [
  "name" => "John",
  "age" => 30,
  "city" => "New York"
];

echo $person["name"]; // John
echo $person["city"]; // New York
  

🧳 3. Multidimensional Arrays

These are arrays that contain other arrays. They are useful for storing complex data structures like records or tables.

$students = [
  "John" => ["age" => 20, "grade" => "A"],
  "Jane" => ["age" => 22, "grade" => "B"],
  "Bob"  => ["age" => 21, "grade" => "A"]
];

echo $students["John"]["grade"]; // A
echo $students["Jane"]["age"];   // 22
  

Loop Example:

foreach ($students as $name => $info) {
  echo "$name - Age: " . $info["age"] . ", Grade: " . $info["grade"] . "<br>";
}
  

📌 Summary Table

Type Description Access Example
Indexed Array Uses numeric indexes (0, 1, 2...) $fruits[1]
Associative Array Uses named keys $person["name"]
Multidimensional Array Arrays inside arrays $students["John"]["age"]

💡 Best Practices:

  • Use short syntax [] for cleaner code
  • Always loop with foreach for readability
  • Use associative arrays when keys have meaning
  • Structure multidimensional arrays clearly and access carefully

Post a Comment

0 Comments