PHP Foreach Loop

The foreach loop in PHP is used to iterate through each element in an array or the properties of an object. It is a convenient way to handle collections in PHP.

Tutorials dojo strip

The foreach Loop for Arrays

The foreach loop is most commonly used to loop through the elements of an array.

Example: Looping Through Motorcycle Brands

PHP

Explanation:

  • The array $motorcycleBrands contains several motorcycle brand names.
  • During each iteration, the current value of the array is assigned to the variable $brand and can be used within the loop.
  • The loop continues until all brands are processed.

Working with Keys and Values

When using associative arrays, you can access both the keys and values in the loop.

Example: Brand Names and Countries

PHP

Explanation:

  • $brand holds the array key (e.g., "Suzuki").
  • $origin contains the corresponding value (e.g., "Japan").
  • This allows you to access both the key and value of each element in the array.

The foreach Loop for Objects

The foreach loop can also be used to iterate through an object’s properties.

Example: Motorcycle Details

PHP

Explanation:

  • The loop iterates through each property ($property) and its corresponding value ($value) in the object $myBike.

Controlling the Loop: Break and Continue

You can control the execution of the loop using the break and continue statements.

The Break Statement

The break statement stops the loop prematurely:

PHP

Explanation:

  • The loop stops as soon as it encounters "Honda".

The Continue Statement

The continue statement skips the current iteration and moves to the next:

PHP

Explanation:

  • The loop skips "Honda" and continues with the remaining brands.

Modifying Array Items by Reference

By default, changes to an array item inside a foreach loop do not affect the original array. However, you can modify the original array using the & symbol.

Example: Changing a Brand Name

PHP

Explanation:

  • The & symbol makes changes to the array items directly affect the original array.
  • In this case, "Honda" is replaced with "Ducati".

Alternative Syntax

The foreach loop can also be written using the endforeach keyword.

Example: Loop Through Brands

PHP
Tutorials dojo strip