Foreach

Foreach is the most popular loop in PHP.

The foreach() loop uses all the elements of the source, and assign them to the blind variable. By default, only the value is assigned; when using the $key => $value syntax, the key is also assigned. Then the block is executed with the assigned values.

Part of the block execution may be skipped by using the continue keyword.

The value may be a reference : then it actually references the original value, which then may be modified in the source. Do not forget to unset referenced variables after the loop, to avoid the dangling reference syndrome, when the last value is changed.

The value may be an array, collecting several values at the same time.

<?php

/*
foreach($source as $key => $value) {
     // block
}
*/

foreach([11,12,13] as $id => $value) {
    print "$id => $value\n";
    // 0 => 11
    // 1 => 12
    // 2 => 13
}

foreach([[21,22], [33, 34]] as [$a, $b]) {
    print "$a $b\n";
    // 21 22
    // 33 34
}

?>

Documentation

Related : Continue, For, Loops, While, Do While