如何测试数组指针是否位于foreach循环中的第一个元素

Ale*_*nch 13 php foreach

在for循环中它很简单......

for ( $idx = 0 ; $idx < count ( $array ) ; $idx ++ )
{
    if ( $idx == 0 )
    {
        // This is the first element of the array.
    }
}
Run Code Online (Sandbox Code Playgroud)

怎么在foreach循环中完成这个?

是否有类似的功能is_first()

我正在寻找类似的东西:

foreach ( $array as $key => $value )
{
    if ( /* is the first element */ )
    {
        // do logic on first element
    }
    else
    {
        // all other logic
    }
}
Run Code Online (Sandbox Code Playgroud)

我想我可以设置一个bool $is_first = true;,然后一旦循环迭代一次,将bool设置为false.

但是php有很多预先构建的功能,并且使用...或者其他方式...

整个博尔的方式看起来几乎像是... cheeting:s

干杯,

亚历克斯

小智 20

我经常这样做:

$isFirst = true;
foreach($array as $key => $value){
  if($isFirst){
    //Do first stuff
  }else{
    //Do other stuff
  }
  $isFirst = false;
}
Run Code Online (Sandbox Code Playgroud)

显然可以使用任何类型的数组.


Rob*_*US2 14

你可以使用"current()"来做到这一点

$myArray = array('a', 'b', 'c');
if (current($myArray) == $myArray[0]) {
    // We are at the first element
}
Run Code Online (Sandbox Code Playgroud)

文件:http://php.net/manual/en/function.current.php

检索第一个元素的方法:

$myArray[0]

$slice = array_slice($myArray, 0, 1); 
$elm = array_pop($slice);
Run Code Online (Sandbox Code Playgroud)

  • 只要它不是关联数组,或者是第一个键为0的索引 (7认同)

Mar*_*ker 5

$myArray = array('a' => 'first', 'b' => 'second', 'c' => 'third'); 

reset($myArray);
$firstKey = key($myArray);
foreach($myArray as $key => $value) {
    if ($key === $firstKey) {
        echo "I'm Spartacus" , PHP_EOL;
    }
    echo $key , " => " , $value , PHP_EOL;
}
Run Code Online (Sandbox Code Playgroud)