how to test if array pointer is at first element in foreach loop

I usually do this :

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

Works with any type of array, obviously.


you can use counter instead bool

$i = 0;

foreach ( $array as $key => $value )

    if ($i == 0) {
        // first
    } else  {
        // last
    }
    // …
    $i++;
}

or extract the first element by

$first = array_shift($array);

and foreach over the remain array;


$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;
}

You can do this using "current()"

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

Docs: http://php.net/manual/en/function.current.php

Ways of retrieving the first element:

$myArray[0]

$slice = array_slice($myArray, 0, 1); 
$elm = array_pop($slice);

Tags:

Php

Foreach