A loop with braces causes incorrect output

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 PHP syntax?

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

Edit:

I know that tags are not needed on every line. More precisely: I want to know why two examples give me two different results?

+6
source share
4 answers

Based on the output, I assume that:

 <?php $arr = array(1,2,3,4,5); ?> <?php foreach ($arr as $element) ?> <?php { ?> <?php echo $element; ?> <?php } ?> 

interpreted as:

 <?php $arr = array(1,2,3,4,5); foreach ($arr as $element); { echo $element; } ?> 

Looks like an error in the interpreter? See Rizier123 comments:

  • Not a bug: stackoverflow.com/q/29284075/3933332
  • The brackets after foreach () / do nothing here /; it's just an operator group: php.net/manual/en/control-structures.intro.php

In any case, the code looks awful with the way you wrote it. Please choose a clean code.


After reading the comments on this, I think John Stirling explains this symptom as the best:

Just guess, but maybe? > in the first example, it is actually taken as the end of the operator (loops can be used without curly braces). At this point, the loop happened, and $ element is the last value. Then the brackets are simply taken as a block of code that you echo, and this is 5.

+5
source

You do not need to use <?php and ?> For every single line:

 <?php $arr = array(1,2,3,4,5); foreach ($arr as $element) { echo $element; } ?> 

Or alternative syntax:

 <?php $arr = array(1,2,3,4,5); foreach ($arr as $element) { echo $element; } ?> 

or

 <?php $arr = array(1,2,3,4,5); foreach ($arr as $element): echo $element; endforeach; ?> 

When you do this:

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

PHP does nothing because it sees

 foreach ($arr as $element) { } echo $element; 
0
source

Using <? php> <? php> is your problem.

You complete the foreach context before returning the result and do not execute it in the second.

Take a good look at your examples and you will see what you are doing differently.

0
source

I don’t know why you use so many php tags, but why it doesn’t work! try the following:

 <?php $arr = array(1,2,3,4,5); foreach ($arr as $element) { echo $element; } ?> 
0
source

All Articles