Semicolon after foreach statement has “interesting” result. Why?

不羁的心 提交于 2020-03-20 03:17:11

问题


Just had an AHA! moment with adding a ; after a foreach loop by accident. Funnily this didn't throw an error, but skipped(?) everything in the loops array and just touches the last element.

Test code:

$test_array = array(
    'a' => 'one',
    'b' => 'two',
    'c' => 'three'
);
foreach ( $test_array as $key => $val );
    echo $val;

Question: Why does this happen?


回答1:


A semicolon ends the statement and a foreach statement is similar to a function - it opens up a scope. If you do not open up a multi-line scope with curly brackets, the scope runs to the next semicolon so

foreach ( $test_array as $key => $val );

is the equivalent of

foreach ( $test_array as $key => $val ) { }

Which I believe answers your question as to why it behaves this way.




回答2:


When you do:

foreach ( $test_array as $key => $val );

Here all the foreach is executed (passing by each element) but as you putted a ; there is no other instruction taken advantage of that, instead when it ends all the iteration, $val contains the value of the last element, which you happen to echo in your next instruction:

echo $val;



回答3:


The ; ends the loop, so that would be equivalent to

foreach ( $test_array as $key => $val ){ /* do nothing */ }

at the end of the loop $val has the value of the last key, therefore it echoes it




回答4:


That's standard "feature" of all languages with C-like syntax. Namely,

for (...);

means

for (...) { }

Also, in your case, after foreach loop ends, $val doesn't disappear, but still exists and holds the last value it was assigned to.




回答5:


The loop runs, performing the iterating and condition checking, but nothing else. Then the echo command executes, and at this point $val contains the last value it was assigned. And the last value it was assigned was the the last value from the loop.




回答6:


All you are doing is looping to all but doing nothing beside the last element.



来源:https://stackoverflow.com/questions/16864802/semicolon-after-foreach-statement-has-interesting-result-why

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!