Use Code: BFCM24 to get 58% OFF your annual membership. Expires soon 👇

Introduction To The Foreach Loop In PHP (With Code Examples)

Luis Ramirez Jr
Luis Ramirez Jr
hero image

Are you a PHP Developer who wants to write more efficient loops?

Or perhaps you’re a beginner who’s curious about the power of PHP's foreach loop, or even what it’s used for?

If so, you've landed in the right place! In this beginner's guide, we’ll dive deep into the PHP foreach loop.

I cover everything from its basic syntax to advanced use cases, compare it with other loops, look into controlling its flow, and even tackle complex scenarios with different variable types.

Why care about this topic?

Simply because by improving your grasp on the foreach loop, you can write cleaner, more readable code, and significantly improve your PHP programming skills. So that soon you’ll be handling arrays and objects with ease, while also making your code flexible and efficient!

So grab a coffee and let’s dive in…

What is the PHP foreach loop?

The foreach loop in PHP is a special type of loop designed specifically for iterating through each element of an array or an object.

It provides a straightforward way to traverse collections without needing to initialize a counter variable, check conditions, or increment the counter.

For example

Here's a simple syntax of a foreach loop:

foreach ($array as $value) {
	// Code to be executed
}

So what’s happening here?

In this example, $array is the array you want to loop over, and $value is the placeholder variable that represents the current element in the array during each iteration.

This means that every time the loop runs, $value will hold the value of the current array element.

Sidenote: To learn more about how PHP handles URL routing, see my detailed PHP router guide.

Why use a foreach loop?

The foreach loop simplifies code that needs to operate on each element of an array.

For example

Without foreach, you would typically use a for loop, initializing a counter variable and managing the loop's conditions and increments manually. However, this can lead to more complex and error-prone code.

But using foreach makes the code more readable and easier to maintain.

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

In this example, $fruits is an array consisting of three elements:

  • Apple
  • Banana
  • and Cherry

The foreach loop iterates over all elements of the $fruits array, and the $fruit placeholder variable contains the value of the current array element.

The loop then echoes each fruit in the array, resulting in:

Apple
Banana
Cherry

By using the foreach loop, you can easily and efficiently process each element in an array, making your code cleaner and more intuitive.

TL;DR

The PHP foreach function is a powerful tool for iterating over arrays or objects, providing a more intuitive and cleaner approach than traditional for or while loops, especially when working with collections.

Advantages of foreach over other PHP loops

When it comes to looping through arrays or objects in PHP, you have several options:

  • for loops
  • while loops
  • foreach loops

However, foreach stands out among all of these due to several advantages.

Advantage #1: Readability and ease of use

foreach loops are more readable and simpler to use when dealing with arrays or objects. They eliminate the need for a counter variable or condition checks inside the loop, which are required in for and while loops.

Here's an example to illustrate:

// Using a for loop
$fruits = array("Apple", "Banana", "Cherry");
for($i = 0; $i < count($fruits); $i++) {
	echo $fruits[$i] . "\n";
}

// Using a foreach loop
$fruits = array("Apple", "Banana", "Cherry");
foreach ($fruits as $fruit) {
	echo $fruit . "\n";
}

In the above example, the foreach loop is more straightforward and easier to read, as it directly deals with each element in the array.

Advantage #2: Improved performance on larger arrays

While performance differences between foreach, for, and while loops are usually negligible for small arrays, foreach can be more efficient for larger arrays and object structures.

This is because it doesn't require evaluating a condition for each iteration like for and while loops do.

Advantage #3: Simplified iteration over associative arrays

foreach is particularly useful for iterating over associative arrays. It allows you to easily access both keys and values without additional code:

$userInfo = array("name" => "John", "email" => "john@example.com");

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

In this example, foreach makes it easy to access and display both the keys and values of the $userInfo array.

Advantage #4: Automatic handling of array pointers

When using foreach, PHP automatically handles the internal array pointer, ensuring that it starts from the beginning of the array and moves through each element.

This reduces the likelihood of errors that can occur when manually managing array pointers with functions like current(), next(), and reset().

Advantage #5: Less error-prone

Because foreach abstracts away the need for manual index handling and condition checks, it reduces the likelihood of common errors, such as off-by-one errors or forgetting to update the loop counter.

This leads to more robust and maintainable code.

TL;DR

While for and while loops have their own use cases, when it comes to iterating over arrays and objects in PHP, foreach provides several advantages.

It offers cleaner, more readable code, simplified handling of associative arrays, automatic array pointer management, and can potentially provide performance benefits in certain scenarios.

How to use the PHP foreach loop: Basic usage to advanced scenarios

We've seen how PHP's foreach loop can iterate through an array and handle each element. But the foreach loop is more flexible than that, capable of handling various scenarios.

Basic usage

We've discussed the basic usage of foreach with a simple array

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
	echo $fruit . "\n";
}

This basic usage is perfect for simple tasks where you need to process each element in an array individually. It’s clean, concise, and easy to understand.

Handling key-value pairs

Sometimes, we need access to both the key and value in an associative array. For such scenarios, foreach offers a variant that can handle key-value pairs:

$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");

foreach ($fruits as $key => $value) {
	echo "Key: $key, Value: $value\n";
}

When working with associative arrays, accessing both the key and values is essential for tasks such as creating HTML elements with attributes, processing form data, or handling configuration settings.

Dealing with multidimensional arrays

foreach can also handle multidimensional arrays.

For example

$fruits = array(
	"summer" => array("Mango", "Cherry"),
	"winter" => array("Apple", "Banana"),
);

foreach ($fruits as $season => $fruitList) {
	echo "$season:\n";
	foreach ($fruitList as $fruit) {
    	echo "- $fruit\n";
	}
}

Why use this?

Multidimensional arrays are common in complex data structures, such as JSON responses from APIs, nested data from databases, or grouped sets of information.

foreach simplifies accessing and manipulating these nested arrays.

Iterating over objects

The foreach loop can also iterate over objects, making it useful for object-oriented programming.

Here's an example with a simple class:

class Fruit {
	public $name;
	public $color;

	public function __construct($name, $color) {
    	$this->name = $name;
    	$this->color = $color;
	}
}

$apple = new Fruit("Apple", "Red");
$banana = new Fruit("Banana", "Yellow");

$fruits = array($apple, $banana);

foreach ($fruits as $fruit) {
	echo "Name: " . $fruit->name . ", Color: " . $fruit->color . "\n";
}

Why use this?

Iterating over objects is useful when working with collections of objects in object-oriented programming.

It allows you to easily process each object in a collection, such as displaying properties or calling methods.

Modifying array elements

You can also use foreach to modify array elements directly.

To do this, use the reference operator &, like so:

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as &$fruit) {
	$fruit = strtoupper($fruit);
}

print_r($fruits);

This will output:

Array
(
	[0] => APPLE
	[1] => BANANA
	[2] => CHERRY
)

Modifying array elements in place is useful for tasks such as normalizing data (e.g., converting all strings to uppercase), applying transformations, or updating values based on certain conditions.

Important: Be cautious when using references!

If you need to update the elements of an array in place, using a reference allows you to modify the original array elements directly without needing to access them by their index.

However, using references can introduce potential pitfalls, such as unintended array modifications or lingering references.

For example

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as &$fruit) {
	echo $fruit . "\n";
}

Here you can see the potential issue:

$fruit = "Grape"; // Without unset, this changes the last element of $fruits to "Grape"

And here’s the solution!

unset($fruit); // Breaks the reference to the array element
$fruit = "Grape"; // Now, this modification does not affect $fruits

So as you can see, while using references can be memory efficient and convenient for updating array elements, it’s crucial to unset the reference after the loop to avoid unintended side effects and ensure code maintainability.

Using list() for working with complex data

The list() function in PHP is a language construct used to assign a list of variables in one operation.

When combined with a foreach loop, it can be especially useful for iterating through arrays where each element itself is an array, and you want to assign each sub-array's elements to variables for easier access.

For example:

$people = [
	['John', 'Doe', 30],
	['Jane', 'Doe', 28],
	['Alice', 'Smith', 34]
];

foreach ($people as $person) {
	list($firstName, $lastName, $age) = $person;
	echo "Name: $firstName $lastName, Age: $age<br>";
}

Why use this?

Using list() with foreach simplifies the code when dealing with multi-dimensional arrays or arrays of arrays.

It also allows for direct unpacking of array elements into separate variables, which makes the code more readable and concise.

Psst: Alternative option in PHP 7.1+

Starting from PHP 7.1, you can also use the square bracket syntax to achieve the same effect in a slightly different way:

foreach ($people as [$firstName, $lastName, $age]) {
	echo "Name: $firstName $lastName, Age: $age<br>";
}

Why use this alternative option?

This newer syntax avoids explicitly calling list() and directly unpacks the elements into variables as part of the foreach statement itself.

This approach is also more streamlined and reduces the amount of code.

Controlling loop flow with break and continue statements

While iterating over arrays or objects using a foreach loop, you might need to control the loop's flow based on certain conditions.

The good news it that PHP offers several ways to do this, including using break and continue statements, so let's take a look at this now.

The break statement

The break statement allows you to exit the loop prematurely. It is particularly useful when you've found what you were looking for and don't need to check the rest of the array.

For example

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
	if ($fruit == "Banana") {
    	break; // Exit the loop as we found the Banana
	}
	echo $fruit . "\n";
}

Using break helps in scenarios where continuing the loop is unnecessary after meeting a certain condition.

For example, if you are searching for a specific item in a list and you find it, there's no need to keep iterating through the remaining elements. This can improve the performance of your script by reducing the number of iterations.

In the example above, the loop will stop iterating once the fruit "Banana" is found, so only "Apple" will be echoed before the loop exits.

The continue statement

The continue statement allows you to skip the rest of the current loop iteration and proceed with the next one. This is useful when you want to avoid certain values in the array.

Here’s how you can do it:

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
	if ($fruit == "Banana") {
    	continue; // Skip the Banana
	}
	echo $fruit . "\n";
}

The continue statement is helpful when you want to skip processing certain elements based on a condition. For instance, if you want to process all items except a specific one, continue allows you to easily skip over that item without breaking the loop entirely.

In the example above, the "Banana" will not be echoed, and the script will continue to the next item in the array, resulting in:

Apple
Cherry

Combining break and continue for complex logic

In more complex scenarios, you might find yourself needing to use both break and continue within the same loop to handle different conditions.

Here’s an example:

$fruits = array("Apple", "Banana", "Cherry", "Date");

foreach ($fruits as $fruit) {
	if ($fruit == "Banana") {
    	continue; // Skip the Banana
	}
	if ($fruit == "Cherry") {
    	break; // Exit the loop when Cherry is encountered
	}
	echo $fruit . "\n";
}

Why combine break and continue?

Combining these control statements allows you to create sophisticated loop logic. For example, you can skip certain elements while stopping the loop entirely when another condition is met.

This approach is useful in data filtering, searching, or any process where conditional handling is required.

In the example above, "Banana" will be skipped, and the loop will terminate when "Cherry" is encountered.

This means that the new output will be:

Apple
Date

TL;DR

As you can see, and as I’ve said before - knowing how to use foreach effectively can help you write cleaner, more efficient code.

From simple arrays to key-value pairs, multidimensional arrays, and objects, PHP's foreach loop offers a flexible way to iterate over data structures. It also allows for modifying elements and controlling loop flow with break and continue.

Sidenote: For additional PHP functionality, such as handling strings, check out my PHP explode guide.

Now let's take it a step further and look at how to handle different variables with this feature.

How to handle different types of variables with PHP foreach

PHP's foreach loop is primarily designed to work with arrays and objects, but understanding how it handles different types of variables is crucial.

So let's break down some of the main options.

foreach with scalar variables

If you attempt to use a scalar variable (like an integer, string, or boolean) with a foreach loop, PHP will throw a warning.

For example:

$number = 42;

foreach ($number as $n) {
	echo $n;
}

Why avoid this?

Simply because scalar variables are single values and do not contain multiple elements to iterate over, hence why it won't work.

In fact, attempting to use foreach with scalars results in a warning because foreach expects an iterable structure.

Warning: Invalid argument supplied for foreach()

Using foreach with arrays

As we've seen, foreach excels when used with arrays.

But did you know it can also handle both indexed arrays and associative arrays, like so…

Indexed arrays example

$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
	echo $fruit . "\n";
}

Using foreach with indexed arrays allows you to process each element in a straightforward manner, enhancing readability and maintainability of the code.

Associative arrays example

$fruits = array("a" => "Apple", "b" => "Banana", "c" => "Cherry");

foreach ($fruits as $key => $value) {
	echo "Key: $key, Value: $value\n";
}

When dealing with associative arrays, accessing both keys and values is essential for various tasks such as creating mappings, generating dynamic content, or processing configuration data.

Using foreach with objects

foreach can also be used with objects!

Hpwever, when used with an object, foreach treats public properties as array elements, like so:

class Fruits {
	public $apple = 'Apple';
	public $banana = 'Banana';
	public $cherry = 'Cherry';
}

$fruits = new Fruits;

foreach ($fruits as $fruit) {
	echo $fruit . "\n";
}

The cool thing about this, is that iterating over an object’s public properties using foreach allows you to easily access and manipulate the properties without needing to know their names beforehand.

This is particularly useful in dynamic scenarios where object properties might change.

Handling iterable objects

PHP also supports iterating over objects that implement the Iterator interface.

For example:

class MyCollection implements Iterator {
	private $items = ["Apple", "Banana", "Cherry"];
	private $index = 0;

	public function current() {
    	return $this->items[$this->index];
	}

	public function key() {
    	return $this->index;
	}

	public function next() {
    	$this->index++;
	}

	public function rewind() {
    	$this->index = 0;
	}

	public function valid() {
    	return isset($this->items[$this->index]);
	}
}

$collection = new MyCollection();

foreach ($collection as $item) {
	echo $item . "\n";
}

Implementing the Iterator interface allows you to create custom iterable objects, giving you fine-grained control over how the object’s data is accessed and iterated.

This is useful for complex data structures and collections.

Time to put this knowledge into action!

As you can see, PHP's foreach loop is incredibly versatile and can handle arrays and objects efficiently.

However, it's important to remember that foreach is intended primarily for iterative structures like arrays and objects and that using it with scalar types causes an error.

Hopefully this guide has set your mind ablaze with ideas of how you can use this loop in your own code and improve your own projects!

P.S.

If you want to learn more about these loops and every other important aspect of PHP, check out my complete course on modern PHP.

learn modern php

I guarantee that this is the most comprehensive and up-to-date PHP Bootcamp course available today. It will help you to go from absolute beginner to mastering PHP web development, getting hired, and advancing your career.

All you need is some basic HTML and CSS experience, and by the end, you’ll have a brand new PHP project to add to your portfolio.

And as an added bonus?

When you take this course and join the Zero To Mastery Academy, you’ll also have access to every Web Development course that we have (as well as every other course), so you can follow a complete path to becoming a working professional Web Developer.

Not only that, but you also get access to our private Discord server!


You can ask questions to me directly (or any teacher) as well as fellow students and working professionals.

So what are you waiting for? Join now, and I’ll see you in Discord!

More from Zero To Mastery

How To Become A Web Developer (From Complete Beginner to Hired) preview
How To Become A Web Developer (From Complete Beginner to Hired)

Want to become a Web Developer but not sure how? Our step-by-step guide shows you how to go from beginner to hired (without wasting $1,000s on a bootcamp or degree). And we answer all your FAQ.

Beginner's Guide to PHP explode() Function (With Code Examples!) preview
Beginner's Guide to PHP explode() Function (With Code Examples!)

Are you a developer wanting to master PHP? Discover how to use explode() to parse strings, handle CSVs, and enhance your data manipulation skills efficiently!

How To Create A Custom PHP Router preview
Popular
How To Create A Custom PHP Router

Learn how to set up a PHP router for your website with this easy-to-follow step-by-step tutorial (with code examples).