8 / 100 SEO Score

Arrays and Loops in PHP

In the previous chapter, we learned about variables, data types, operators, and conditionals.
Now, let’s move one step ahead and explore Arrays and Loops — two very important parts of PHP programming.

👉 Arrays help us store multiple values inside a single variable.
👉 Loops help us run the same block of code multiple times without repeating it manually.

By the end of this chapter, you will be able to:

  • Use indexed, associative, and multidimensional arrays
  • Perform operations like adding, updating, removing, sorting, and slicing arrays
  • Use different types of loops (for, while, do-while, foreach)

📌 Arrays in PHP

An array is a special variable that can hold more than one value at a time.

1. Indexed Arrays

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

<?php
$students = array("Jill", "Michael", "John", "Sally");

// Print first student
echo $students[0]; // Output: Jill

// Add new student
$students[] = "Tom";

// Remove a student
unset($students[2]); // removes John
?>

2. Associative Arrays

Associative arrays use names (keys) instead of numbers.

<?php
$michael = array(
  "age" => 20,
  "gender" => "male",
  "favorite_color" => "blue"
);

// Print Michael's age
echo $michael["age"]; // Output: 20

// Add new data
$michael["occupation"] = "Sales Associate";

// Remove data
unset($michael["occupation"]);
?>

3. Multidimensional Arrays

Multidimensional arrays are arrays inside arrays.

<?php
$students = array(
  "Jill" => array(
    "age" => 20,
    "gender" => "female",
    "favorite_color" => "red"
  ),
  "Amy" => array(
    "age" => 25,
    "gender" => "female",
    "favorite_color" => "green"
  )
);

echo $students["Jill"]["age"]; // Output: 20
?>

4. Useful Array Functions

  • explode() → convert string into array
  • implode() → convert array into string
  • array_slice() → take a part of an array
  • ksort() → sort an array by keys

Example:

<?php
$filename = "myexamplefile.txt";

// Break into parts
$parts = explode(".", $filename);
echo $parts[0]; // Output: myexamplefile

// Rebuild with changes
$parts[0] .= "_v1";
$new_file = implode(".", $parts);
echo $new_file; // Output: myexamplefile_v1.txt
?>

📌 Loops in PHP

Loops are used when you want to repeat tasks without writing the same code again.

1. For Loop

Best when you know how many times the loop should run.

<?php
for($i = 0; $i < 5; $i++) {
  echo "Count: $i \n";
}
?>

2. While Loop

Runs as long as the condition is true.

<?php
$count = 1;
while($count <= 5){
  echo "Count: $count \n";
  $count++;
}
?>

3. Do-While Loop

Runs the code at least once, then checks the condition.

<?php
$count = 1;
do {
  echo "Count: $count \n";
  $count++;
} while($count <= 5);
?>

4. Foreach Loop

Specially made for arrays.

<?php
$students = array("Jill", "John", "Tom");

foreach($students as $student){
  echo $student . "\n";
}
?>

With key-value pairs:

<?php
$employees = array(
  array("name" => "John Doe", "title" => "Programmer", "salary" => 60000),
  array("name" => "Jane Smith", "title" => "Manager", "salary" => 120000)
);

foreach($employees as $employee){
  echo $employee["name"] . " (" . $employee["title"] . ") earns $" . ($employee["salary"]/12) . " per month.\n";
}
?>

🎯 Summary

  • Arrays store multiple values (indexed, associative, multidimensional).
  • We can add, update, delete, and sort arrays using built-in functions.
  • Loops (for, while, do-while, foreach) help repeat code easily.

👉 In the next chapter, we’ll learn about functions and classes to make our code reusable.


Tip: Practice arrays and loops with small programs. The more you practice, the easier it becomes

Leave a Comment