foreach语句后的分号具有"有趣的"结果。为什么? [英] Semicolon after foreach statement has "interesting" result. Why?
问题描述
只是有一个的 AHA 的时刻与加入; <!/ code> A
的foreach
循环结束后意外地。有趣地这并不会引发错误,但跳过(?)的循环数组中的一切,刚好碰到的最后一个元素。
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.
测试code:
$test_array = array(
'a' => 'one',
'b' => 'two',
'c' => 'three'
);
foreach ( $test_array as $key => $val );
echo $val;
问:为什么会出现这种情况。
Question: Why does this happen?
推荐答案
一个分号结束语句和foreach语句是类似的功能 - 它开辟了一个范围。如果你不打开了花括号多行范围,范围内运行到下一个分号,所以
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 );
是等效
foreach ( $test_array as $key => $val ) { }
我相信这回答你的问题,为什么它的行为这样。
Which I believe answers your question as to why it behaves this way.
这篇关于foreach语句后的分号具有&QUOT;有趣的&QUOT;结果。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!