Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop with curly brackets causes wrong output

Tags:

loops

foreach

php

I created 2 simple examples:

First example:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) ?>
<?php { ?>
    <?php echo $element; ?>
<?php } ?>

output:

5 //Is this result wrong?

Second example:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) { ?>
    <?php echo $element; ?>
<?php } ?>

output:

12345

What did I miss about the PHP syntax?

I know that there is an alternative foreach syntax, but in my opinion both shown examples should result in the same output. (Code tested with PHP version: 5.6.12)

Edit:

I know the tags are not needed in every line. To be more precise: I want to know why the two examples give me 2 different results?

like image 326
Thulur Avatar asked Aug 27 '15 12:08

Thulur


1 Answers

Based on the output, my guess is that:

<?php $arr = array(1,2,3,4,5); ?>

<?php foreach ($arr as $element) ?>
<?php { ?>
    <?php echo $element; ?>
<?php } ?>

is being interpreted as:

<?php
$arr = array(1,2,3,4,5);

foreach ($arr as $element);
{
    echo $element;
}
?>

Looks like a bug in the interpreter? See comments by Rizier123:

  1. Not a bug: stackoverflow.com/q/29284075/3933332
  2. The brackets after the foreach()/Do nothing here/; is just a statement-group: php.net/manual/en/control-structures.intro.php

Anyways, the code looks atrocious with the way you have written it. Please opt for cleaner code.


Reading through the comments under the question I think Jon Stirling explain this symptom the best:

Just guessing, but perhaps the ?> in the first example is actually being taken as the statement end (loops can be used without braces). At that point, the loop has happened and $element is the last value. Then the braces are just take as a code block which you echo, which is 5.

like image 51
MonkeyZeus Avatar answered Oct 14 '22 05:10

MonkeyZeus