The PHP FOREACH function is an excellent method for iterating through a PHP array or an object. In fact, it’s the best method for iterating through an array or an object. Even better, it’s pretty easy to use.

Today, we’re going to take a look at the PHP FOREACH function, how it’s used, and what some alternatives might be.

Let’s get started!

The PHP FOREACH function

The FOREACH construct is easy to build, though do recall that it works only on arrays and objects. 

We’re going to start with the most basic syntax. 

foreach($array as $item) {
		$code_block;
	}

In the above syntax, the parameters are:

FOREACH is a little unique because it involves a temporary variable. Each item in the array becomes the temporary variable for the scope of the code block. Within the FOREACH statement, you’ll use that temporary variable name to refer to the current value. The current value will always hold the current internal array pointer.

PHP for Beginners – Become a PHP Master – CMS Project

Last Updated October 2022

Bestseller
  • 336 lectures
  • All Levels
4.3 (24,122)

PHP for Beginners: learn everything you need to become a professional PHP developer with practical exercises & projects. | By Edwin Diaz, Coding Faculty Solutions

Explore Course

How to use the PHP FOREACH function

The easiest way to understand PHP FOREACH is to look at a FOREACH array example. The following code creates an array of programming languages and then iterates through that array of programming languages.

$programming_languages = array('PHP','C','Java','Python');

foreach($programming_languages as $current_language) {
	print("Learn $current_language now on Udemy!<br>");
}

And the results: 

An example using a FOREACH loop in PHP.

As you can see, the $current_language element gets assigned within the code block, so it always refers to the current element. This is what makes FOREACH so powerful and so easy to use.

Using FOREACH loops with different array keys

In the first example we gave, the array is quite simple. Slot 0 is the array 0, slot 1 is the array 1, and so forth: there are numerical keys. But what if you have a text-based element key?

We’re using an array to store configuration settings in the next example. Each array element is a variable with a different data type, and each element key is a string rather than a number. 

$config["Programming_Language"] = "PHP";
$config["Strictly_Typed"] = "No";
$config["Version"] = 1;

How do we iterate through this? Luckily, the FOREACH array pointer is advanced enough that it can easily traverse string array elements. But you’ll need a different syntax that considers these key value pairs because you may want to know the key value statement, too.

Let’s take a look at this secondary FOREACH syntax:

foreach($array as $key => $value) {
		$code_block;
	} 

In the above, the parameters are mostly unchanged:

The below example will iterate through our array of string keys while also preserving both the key and its value.

$config["Programming_Language"] = "PHP";
$config["Strictly_Typed"] = "No";
$config["Version"] = 1;

foreach($config as $key => $setting) {
	print("$key: $setting<br>");
}
PHP code using FOREACH with string keys.

This is also how you use PHP FOREACH to iterate through objects — which is the next topic for discussion.

Top courses in PHP

APIs in PHP: from Basic to Advanced
Dave Hollingworth
4.6 (802)
Laravel 10 – Build Real Estate Property Listing Project A-Z
Kazi Ariyan, easy Learning
4.8 (137)
Highest Rated
PHP for Beginners – Become a PHP Master – CMS Project
Edwin Diaz, Coding Faculty Solutions
4.3 (24,122)
Bestseller
PHP with Laravel for beginners – Become a Master in Laravel
Edwin Diaz, Coding Faculty Solutions
4.4 (12,515)
Object Oriented PHP & MVC
Brad Traversy
4.5 (4,831)

More PHP Courses

Using PHP FOREACH to iterate through objects

An object can be treated as an array for the purposes of the PHP FOREACH function. Let’s begin with a simple class in PHP:

class Student
{
public $first_name = "John";
    	public $last_name = "Doe";
    	public $email = "[email protected]";
}

$class = new Student();

We will iterate through this class exactly as we iterated through an array:

foreach($class as $key => $value) {
	print("$key: $value<br>");    
}
Iterating through a class object using an array in PHP.

As you can see, we could iterate through the object the same as an array, and we were able to iterate through all the variables.

But here’s something to consider: What happens if we set the email address to a private variable?

Using FOREACH with a class with public and private variables.

Note that the array iteration will only occur through public variables, not private variables. Private variables have a limited scope; only the class student can access that variable. 

PHP FOREACH functions and different types of variables

Before, we’ve discussed that PHP is somewhat unique in that it’s not strictly typed by default. That means you can have an array with multiple types of variables in it. Consider the following array:

	$variables = array('One','2',3,3.0);

This is a valid array in PHP and wouldn’t be a valid array in many other languages. It contains a string, a number as a string, a number, and a floating point. Let’s run this array through a FOREACH loop.

$variables = array("One","2",3,3.0);

foreach($variables as $key => $value) {
	print("$key: $value<br>");
    
}
Using a multi-typed array in a FOREACH loop.

That runs just fine. But the danger when using a FOREACH loop is that you might treat your “$value” as a specific type. For most operations, this will work fine (PHP will treat a string 2 as an int 2). Some operations in PHP are strictly typed and will not allow this.

FOR vs. FOREACH loops in PHP 

An alternative to the PHP FOREACH loop is the PHP FOR loop. FOR loops are the best loop for iterating code until a given condition is met. FOREACH loops are the best loop for iterating through arrays. But in reality, there are many types of loops, and both can be used pretty effectively.

Let’s go back to our first example:

$programming_languages = array('PHP','C','Java','Python');

foreach($programming_languages as $current_language) {
	print("Learn $current_language now on Udemy!<br>");
}

In a FOR loop, it would be written like this:

$programming_languages = array('PHP','C','Java','Python');

for($i = 0; $i < sizeof($programming_languages); $i++) {
	print("Learn $programming_languages[$i] now on Udemy!<br>");
}

When we run the above code, we see that it works exactly the same:

Using a FOR loop instead of a FOREACH loop in PHP.

Some programmers prefer using FOR loops for everything. There’s no real reason not to, except that FOREACH loops are easier to read and easier to use. As you can see, in the FOR loop, we need to refer to $array[$key] rather than just $temporary_variable. Using a $temporary_valuable generally makes for more readable code.

Using PHP FOREACH to iterate through arrays and objects

You now know everything you need to know about using the PHP FOREACH function and syntax to iterate through arrays and objects. FOREACH is a compact, easy-to-use function, and it can be compelling when used correctly.

To learn more about PHP, consider taking a PHP course.

Page Last Updated: March 2022