php foreach endforeach

Syntax with "endforeach" used mostly in complex templates where easier to find "endforeach" than "}":

<?php
foreach ($arr as $key => $value):
	echo 'Key: '.$key.' Value: '.$value."<br />\n";
endforeach; 
?>

Classic syntax:

<?php
foreach ($arr as $key => $value){
	echo 'Key: '.$key.' Value: '.$value."<br />\n";
}
?>

3 thoughts on “php foreach endforeach”

  1. It is important to note when using alternative syntax for control structures that,

    1) This method can be used for all control structures
    2) You can't use them out of order

    $value ) :
    if ( $value == 'world' ) : print "Not Allowed!" . PHP_EOL; endforeach; endif;
    print "$key => $value" . PHP_EOL;
    endforeach;
    ?>

    This will output a PHP Parse error: syntax error, unexpected 'endforeach', but you can use break.

    $value ) :
    if ( $value == 'world' ) : print "Not Allowed!" . PHP_EOL; break; endif;
    print "$key => $value" . PHP_EOL;
    endforeach;
    ?>

    outputs

    0 => hello\n
    1 => foo\n
    2 => bar\n
    Not Allowed!\n

    Also note that if your control structure only contains one statement you can omit the ":" and "endif;"

    $value ) :
    if ( $value == TRUE ) print "Hello World!" . PHP_EOL;
    else print "Foo Bar!" . PHP_EOL;
    endforeach;
    ?>

    outputs

    Foo Bar!\n
    Hello World!\n

    Reply

Leave a Comment