PHP Control Structures foreach

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

foreach is a construct, which enables you to iterate over arrays and objects easily.

$array = [1, 2, 3];
foreach ($array as $value) {
    echo $value;
}

Outputs: 123.

To use foreach loop with an object, it has to implement Iterator interface.

When you iterate over associative arrays:

$array = ['color'=>'red']; 

foreach($array as $key => $value){
    echo $key . ': ' . $value; 
}

Outputs: color: red

For detailed information, see the Loops topic.



Got any PHP Question?