为何foreach循环无法输出?$arr与$arr[]的区别是什么?
Hey there! Let's break down what's happening here—this behavior can feel super confusing at first, but it all boils down to a subtle quirk in how PHP handles arrays.
Core Differences Between $arr and $arr[]
$arr: This is just direct access to your original array variable. It doesn't modify the array at all; it just refers to it exactly as it exists.$arr[]: This is PHP's shorthand for appending an element to the end of the array. For example,$arr[] = "new_item";adds that string as the last element of$arr. Even if you immediately delete that new element (likeunset($arr[count($arr)-1])), the act of appending something triggers a small but important change in how PHP treats the array.
Why Your Foreach Loop Behaves Differently
The key issue here is PHP's internal array pointer. Every array has a hidden pointer that tracks the current position for functions like current(), next(), or each(). If you (or some code you ran earlier) moved this pointer to the end of the array, here's what plays out:
- When you run
foreach($arr)right away, PHP starts traversing from the current pointer position. If it's already at the end, the loop never runs—even thoughvar_dump($arr)shows the array has elements (sincevar_dumpdoesn't care about the internal pointer state). - When you use
$arr[](even if you add and then remove the temporary element), this operation resets the internal array pointer back to the start of the array. Now when you runforeach($arr), it starts from the beginning and iterates through all elements like you'd expect.
Quick Way to Confirm
Instead of using $arr[], try adding reset($arr); right before your foreach loop. If the loop starts working, that confirms the internal pointer was stuck at the end. The reset() function explicitly moves the pointer back to the first element of the array.
Example to Illustrate
Here's a quick snippet that mirrors your scenario:
// Imagine this code ran earlier—moves the pointer to the end of the array while (next($arr)) { // Some logic here } // This foreach won't output anything foreach ($arr as $item) { echo $item; } // Append a temp element then remove it $arr[] = 'temp'; unset($arr[count($arr)-1]); // Now this foreach works perfectly foreach ($arr as $item) { echo $item; }
That's exactly what's going on—$arr[] is indirectly fixing the internal pointer issue, which makes your loop run, even though var_dump($arr) looks identical before and after.
内容的提问来源于stack exchange,提问作者Thanh Nguyen Van

