In this tutorial, we look at the PHP foreach() loop. We also look at how to use it while working with an indexed or associative array.
This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.
Table of Contents - PHP foreach:
- What is foreach()?
-
Code and Explanation
- Indexed arrays
- Associative arrays
- Closing thoughts
What is foreach in PHP?
The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.
Syntax of PHP foreach():
The foreach() method has two syntaxes, one for each type of array.
The syntax for indexed arrays is as given in the following code block:
foreach (iterable as $value)
statement
The syntax for associative arrays:
foreach (iterable as $key => $value)
statement
Here, “Iterable” is the required parameter. It is the array or the variable containing the array. “$value” is a variable that stores the current element in each iteration.
Associated array, uses keys and values, and hence the $key & $values in the second syntax represent the same accordingly.
Code & Explanation:
In this section, we first look at how the foreach() function works on an indexed array followed by which we look at it’s working on an associative array.
PHP Foreach() on Indexed arrays:
<?php
$flexiple = array("Hire", "top", "freelance", "developers");
foreach ($flexiple as $value) {
echo "$value <br>";
}
?>
The output of the above code snippet would be:
Hire
Top
Freelance
developers
PHP Foreach() on an Associative array:
<?php
$freelancer = array(
"name" => "Eric",
"email" => "Eric@gmail.com",
"age" => 22,
"gender" => "male"
);
// Loop through employee array
foreach($freelancer as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
The output of the above code snippet would be:
name: Eric
email: Eric@gmail.com
age: 22
gender: male
Now let’s look at a case where we pass a second argument. As you can see the key and the values of the associative array were printed. Additionally, we replaced “=>” with a “:” to make it more readable.
Closing thoughts:
The foreach() method would return an error in case you use it on variables with a different data type. Additionally, the foreach() method does not modify the values of the internal pointer.
Once you have understood the working to the foreach() method try working with the for loop.
Top comments (2)
Since
php-5.4
is released, using the short array syntax to replace array syntax.I recommend using the
[]
to replacearray
syntax :).Hey Peter, thanks for you suggestion. I shall definitely try it out. :)