- Instant help with your Php coding problems

Using foreach in php

Question:
How to use foreach in php?
Answer:
$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;
}
Description:

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

There are two syntaxes:

foreach ($myArray as $value) {
    ...
}

or

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:
Tags:
php, loop, foreach, iterate, iterate over all element
Technical term:
Using foreach in php
Interesting things
ChatGPT in a nutshell