- Instant help with your Php coding problems

Using foreach in php

How to use foreach in php?
$myArray = [1,2,3];

foreach ($myArray as $item) {
    echo $item;

$myAssocArray = [1=>'One',2=>'Two',3=>'Three'];

foreach ($myAssocArray as $key => $value) {
    echo $key . ' is ' . $value;

To iterate over all element of an array in PHP you can use the foreach construct. 

There are two syntaxes:

foreach ($myArray as $value) {


foreach ($myArray as $key => $value) {

The first form iterates through $myArray . At each iteration the value of the current element $value is assigned.

In the second form, the key of the current element is additionally assigned to the $key variable at each iteration.

Share "How to use foreach in php?"
Related snippets:
php, loop, foreach, iterate, iterate over all element
Technical term:
Using foreach in php