PHP foreach Loop : A Tutorial with Examples

In PHP, the foreach loop is a control structure specifically designed for iterating over arrays and objects.

It is the easiest and most efficient way to traverse the elements of an array or an object without the need to manually manage the loop counter or access elements by their index.

In this tutorial, we will cover:

Let’s explore each concept with examples and explanations.

1. What is a foreach Loop?

The foreach loop in PHP is designed to iterate over arrays and objects, making it particularly useful for handling arrays with minimal overhead. It simplifies array traversal by eliminating the need for an explicit counter variable or the count() function that is typically needed in for loops.

Key Features:

  • Best suited for arrays and objects: The foreach loop is specifically optimized for iterating over arrays and objects.
  • No need for index management: The loop automatically traverses each element of the array or object.

2. Basic Syntax of foreach Loop

The foreach loop has two common syntaxes: one for retrieving only the values, and another for retrieving both the keys and values.

Syntax (Values Only):

foreach ($array as $value) {
    // Code to execute for each $value
}

Syntax (Keys and Values):

foreach ($array as $key => $value) {
    // Code to execute for each $key and $value pair
}
  • $array: The array to be traversed.
  • $key: The current key in the array (optional).
  • $value: The current value in the array.

3. How the foreach Loop Works

  1. Initialization: The loop initializes by setting $value (and $key, if needed) to the first element of the array.
  2. Execution: The block of code inside the loop is executed for the current element.
  3. Advancement: The loop automatically advances to the next element of the array.
  4. Termination: The loop terminates after processing all elements in the array.

4. Examples of Using the foreach Loop

Example 1: Iterating Over a Simple Array (Values Only)

<?php
$numbers = [10, 20, 30, 40, 50];

foreach ($numbers as $number) {
    echo "Number: $number\n";
}
?>

Output:

Number: 10
Number: 20
Number: 30
Number: 40
Number: 50
  • In this example, the foreach loop iterates over the $numbers array and prints each value.

Example 2: Iterating Over an Associative Array (Keys and Values)

<?php
$person = [
    "name" => "Alice",
    "age" => 25,
    "city" => "New York"
];

foreach ($person as $key => $value) {
    echo "$key: $value\n";
}
?>

Output:

name: Alice
age: 25
city: New York
  • In this example, the foreach loop iterates over the associative array $person and retrieves both the keys and values.

5. Using foreach with Associative Arrays

The foreach loop is especially useful for traversing associative arrays, where each element has a key-value pair. You can access both the key and the value in the loop by using the syntax foreach ($array as $key => $value).

Example: Associative Array Iteration

<?php
$products = [
    "P001" => "Laptop",
    "P002" => "Tablet",
    "P003" => "Smartphone"
];

foreach ($products as $code => $product) {
    echo "Product Code: $code, Product Name: $product\n";
}
?>

Output:

Product Code: P001, Product Name: Laptop
Product Code: P002, Product Name: Tablet
Product Code: P003, Product Name: Smartphone
  • In this example, the foreach loop retrieves both the product code (key) and the product name (value) from the $products associative array.

6. Modifying Array Elements Inside foreach

By default, the foreach loop works with copies of the array elements. However, if you want to modify the array elements directly, you need to pass them by reference using the & operator.

Example: Modifying Array Elements Inside foreach

<?php
$prices = [100, 200, 300];

foreach ($prices as &$price) {
    $price += 50;  // Add $50 to each price
}

print_r($prices);
?>

Output:

Array
(
    [0] => 150
    [1] => 250
    [2] => 350
)
  • In this example, the foreach loop modifies the original array elements by adding 50 to each price. The & operator is used to pass each element by reference.

7. Using break and continue in foreach Loops

break Statement:

The break statement is used to exit the loop early, regardless of the loop condition.

Example (Using break in foreach Loop):

<?php
$fruits = ["Apple", "Banana", "Cherry", "Date"];

foreach ($fruits as $fruit) {
    if ($fruit === "Cherry") {
        break;  // Exit the loop when "Cherry" is found
    }
    echo "Fruit: $fruit\n";
}
?>

Output:

Fruit: Apple
Fruit: Banana
  • In this example, the loop terminates when “Cherry” is found, and no further iterations are executed.

continue Statement:

The continue statement skips the remaining code in the current iteration and moves to the next iteration.

Example (Using continue in foreach Loop):

<?php
$fruits = ["Apple", "Banana", "Cherry", "Date"];

foreach ($fruits as $fruit) {
    if ($fruit === "Banana") {
        continue;  // Skip "Banana"
    }
    echo "Fruit: $fruit\n";
}
?>

Output:

Fruit: Apple
Fruit: Cherry
Fruit: Date
  • In this example, the loop skips the iteration when “Banana” is found, and the rest of the elements are processed.

8. Iterating Over Objects with foreach

The foreach loop can also be used to iterate over objects in PHP. When used with an object, the loop traverses the public properties of the object.

Example: Iterating Over an Object’s Properties

<?php
class Car {
    public $make = "Toyota";
    public $model = "Corolla";
    public $year = 2020;
}

$car = new Car();

foreach ($car as $property => $value) {
    echo "$property: $value\n";
}
?>

Output:

make: Toyota
model: Corolla
year: 2020
  • In this example, the foreach loop iterates over the public properties of the $car object and prints each property name and value.

9. Difference Between for and foreach Loops

Both for and foreach loops can be used to iterate over arrays, but they have different use cases:

for Loop:

  • Best used for: Iterating over indexed arrays where you need access to the index.
  • Requires manual index handling: You must manage the loop counter and access elements using their index.

foreach Loop:

  • Best used for: Iterating over both indexed and associative arrays or objects.
  • No manual index handling: The loop automatically handles the current element, and you can easily access the key-value pairs in associative arrays.

Example: Comparison of for and foreach

<?php
$fruits = ["Apple", "Banana", "Cherry"];

// Using for loop
for ($i = 0; $i < count($fruits); $i++) {
    echo "For loop: $fruits[$i]\n";
}

// Using foreach loop
foreach ($fruits as $fruit) {
    echo "Foreach loop: $fruit\n";
}
?>
  • In this example, both loops achieve the same result, but foreach is more concise and does not require managing an index.

Summary of PHP `

foreach` Loop:

Concept Description
Basic Syntax (Values Only) foreach ($array as $value)
Basic Syntax (Keys and Values) foreach ($array as $key => $value)
Modifying Array Elements Use & to pass elements by reference and modify the original array.
break and continue break exits the loop early, and continue skips to the next iteration.
Iterating Over Objects The foreach loop can traverse the public properties of an object.
Difference from for Loop foreach is more convenient for arrays and objects, while for requires manual index handling.

Conclusion

The foreach loop in PHP is a powerful and convenient tool for iterating over arrays and objects. It simplifies the process of traversing collections by eliminating the need for manual index management. In this tutorial, we covered:

  • The syntax and workings of the foreach loop.
  • Several examples of how to use foreach with indexed arrays, associative arrays, and objects.
  • How to modify array elements inside a foreach loop by reference.
  • Using break and continue to control the flow of the loop.
  • The difference between for and foreach loops and when to use each.

Related posts

PHP Static Methods: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

PHP Copying Files: A Tutorial with Examples