在 for 循环中很简单...
for ( $idx = 0 ; $idx < count ( $array ) ; $idx ++ )
{
if ( $idx == 0 )
{
// This is the first element of the array.
}
}
这到底是如何在 foreach 循环中完成的?
有没有类似is_first()
之类的函数?
我正在寻找类似的东西:
foreach ( $array as $key => $value )
{
if ( /* is the first element */ )
{
// do logic on first element
}
else
{
// all other logic
}
}
我在想我可以设置一个像 $is_first = true;
这样的 bool,然后一旦循环迭代一次,就将 bool 设置为 false。
但是 php 有很多预建函数和 id 而不是使用那个...或其他方式...
整个 bool 方式看起来几乎就像...... cheeting :s
干杯,
亚历克斯
最佳答案
我通常这样做:
$isFirst = true;
foreach($array as $key => $value){
if($isFirst){
//Do first stuff
}else{
//Do other stuff
}
$isFirst = false;
}
显然适用于任何类型的数组。
关于php - 如何测试数组指针是否在foreach循环中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9176810/