In this lesson, you will learn about the foreach loop in PHP, and its usage, along with examples to better understand the topic.
In PHP, the foreach loop provides an easy way to loop over an array. In every loop iteration, the value of the current array element is allocated to the $value variable, and the array pointer is shifted by one until it reaches the last array element.
<?php
foreach ($arrVar as $arrValues)
{
//block of code to be processed here
}
?>
Example
<?php
echo "PHP ***Foreach loop***example";
echo "<br>";
echo " ------------Foreach loop ------------------ ";
echo "<br>";
echo "Names of countries in the array";
echo "<br>";
$country = array(
"Canada",
"America",
"New Zealand"
);
// Loop through country array
foreach ($country as $value)
{
echo $value . "<br>";
}
?>
Output
PHP ***Foreach loop*** example ------------Foreach loop ------------------ Names of countries in the array Canada America New Zealand
Let’s take another instance through an associative array that loops. An associative array for access keys utilizes alphanumeric phrases.
Associative Array Example
<?php
echo "PHP ***Associative Foreach loop***example";
echo "<br>";
echo " ------------foreach loop ------------------ ";
echo "<br>";
$subjectteacher = array(
"Sarah" => "Math",
"Smith" => "English",
"Zain" => "Science"
);
foreach ($subjectteacher as $key => $value)
{
echo "$key teaches $value" . "<br>";
}
?>
Output
PHP ***Associative Foreach loop***example ------------foreach loop ------------------ Sarah teaches Math Smith teaches English Zain teaches Science
In the above example, the teacher names have been used as array keys and subjects as the values.
This concludes the PHP foreach Loop lesson. In the next lesson, we will teach about another type of loop in PHP, the while loop!