問題描述
我有一個 foreach 循環,我想查看循環中是否有下一個元素,以便我可以將當??前元素與下一個元素進行比較.我怎樣才能做到這一點?我已經閱讀了 current 和 next 函數,但我不知道如何使用它們.
I have a foreach loop and I want to see if there is a next element in the loop so I can compare the current element with the next. How can I do this? I've read about the current and next functions but I can't figure out how to use them.
提前致謝
推薦答案
一種獨特的方法是反轉數組和 then 循環.這也適用于非數字索引數組:
A unique approach would be to reverse the array and then loop. This will work for non-numerically indexed arrays as well:
$items = array(
'one' => 'two',
'two' => 'two',
'three' => 'three'
);
$backwards = array_reverse($items);
$last_item = NULL;
foreach ($backwards as $current_item) {
if ($last_item === $current_item) {
// they match
}
$last_item = $current_item;
}
如果您仍然對使用 current
和 next
函數感興趣,您可以這樣做:
If you are still interested in using the current
and next
functions, you could do this:
$items = array('two', 'two', 'three');
$length = count($items);
for($i = 0; $i < $length - 1; ++$i) {
if (current($items) === next($items)) {
// they match
}
}
#2 可能是最好的解決方案.注意,$i <$length - 1;
將在比較數組中的最后兩項后停止循環.我把它放在循環中,以便在示例中明確.你應該只計算 $length = count($items) - 1;
#2 is probably the best solution. Note, $i < $length - 1;
will stop the loop after comparing the last two items in the array. I put this in the loop to be explicit with the example. You should probably just calculate $length = count($items) - 1;
這篇關于獲取 foreach 循環中的下一個元素的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!