3

I was reading through a php to python article which was talking about pythons equivalent of foreach() they gave the php code example as

foreach ( $items as $item )
    echo $item;

Is this a valid syntax without the {} ive always seen it written as

foreach ( $items as $item ){
    echo $item;
}

I ran the first example through coderunner locally to see if it would through an error and it didnt, is this a valid syntax to use or will i run into problems using it ?

sam
  • 9,486
  • 36
  • 109
  • 160

4 Answers4

13

Treat foreach and { ... } as 2 different and independent language constructs.

The original foreach syntax is

foreach (...)
    statement

echo $item; is a valid statement.

{ // any code here } is a single valid statement as well.

zerkms
  • 249,484
  • 69
  • 436
  • 539
4

Yes this is valid. I have often seen this written as

<?php 
foreach($array as $element): 
  //do something 
endforeach; 
?>

See - http://www.php.net/manual/en/control-structures.foreach.php

x20mar
  • 479
  • 5
  • 17
  • 8
    this is different and used in templating more. It supports 2 or more lines between opening and ending – Royal Bg Jan 12 '14 at 22:35
2

It is valid assuming that there is one statement "inside" the foreach loop. This actually generalizes beyond foreach, it works for for, while, if, etc. Additionally, it is not specific to PHP, many languages support this single-statement short hand.

asimes
  • 5,749
  • 5
  • 39
  • 76
0

Yes this is a valid example. It will only work if there is one statement to be executed, or the statement cascades into another conditional/statement.

So while the following example is not valid, (that is only the first echo will be executed within the loop).

foreach( ... )
    echo ...
    echo ...

This example still is

foreach( ... )
    if( ... )
        echo ...    
Digital Fu
  • 2,877
  • 1
  • 14
  • 20
  • "one line in the statement" --- ? `echo 'foo \n bar';` (where `\n` is a real new line). Or `echo 1; echo 2;` --- still one line. It has **nothing** to do with number of lines there. It must be rewritten to remove any mentions of lines. – zerkms Jan 12 '14 at 22:57
  • Your quite right, fixed. – Digital Fu Jan 12 '14 at 23:03