在一个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有很多pre-built函数和id,而是使用…或另一种方式…
整个布尔方式似乎几乎像…欢呼:s
干杯,
亚历克斯
你可以使用“current()”
$myArray = array('a','b','c');
if (current($myArray) == $myArray[0]) {
// We are at the first element
}
文件:http://php.net/manual/en/function.current.php
检索第一个元素的方法:
$myArray[0] $slice = array_slice($myArray,1); $elm = array_pop($slice);