PHP - 抓住第一个元素使用foreach [英] PHP - Grab the first element using a foreach
本文介绍了PHP - 抓住第一个元素使用foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在第一次迭代时做一些不同的事情。
对于这些情况,我们是最好的选择吗? 是的,如果你不能通过一个不同的方式(一个正常的循环)通过对象,只需在这种情况下使用条件:
$ first = true;
foreach($ obj as $ value)
{
if($ first)
{
//做某事
$ first = false;
}
else
{
//做某事
}
//做某事
}
Wondering what would be a good method to get the first iteration on a foreach loop. I want to do something different on the first iteration.
Is a conditional our best option on these cases?
解决方案
Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:
$first = true;
foreach ( $obj as $value )
{
if ( $first )
{
// do something
$first = false;
}
else
{
// do something
}
// do something
}
这篇关于PHP - 抓住第一个元素使用foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文