the most common task with arrays is to do something with every element for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, there are several ways to traverse arrays in PHP and the one you choose will depend on your data and the task you’re performing.
foreach loop
foreach loop is use to iterate over arrays. For every counter of loop, an array element is assigned and the next counter is shifted to the next element.
Syntax = foreach (array_element as value)
{
//code to be executed
}
Flow diagram
example1
<?php
// for index array
$subjects = [
"c++",
"php",
"java"
];
foreach($subjects as $value)
{
echo $value . "<br>";
}
?>
output
c++
php
java
example2
<?php
// for associative array
$subjects = [
"c++" => 24,
"php" => 25,
"java" => 26
];
foreach($subjects as $key => $value )
{
echo "$key = $value <br>";
}
?>
output
c++ = 24
php = 25
java = 26