15

In a for loop it is simple...

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

How the hell is this done in a foreach loop?

is there a function like is_first() or something?

I'm looking for something like:

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

I was thinking I could set a bool like $is_first = true; and then as soon as the loops been iterated once, set the bool to false.

But php has a lot of pre-built functions and id rather use that... or another way...

The whole bool way seem almost like... cheeting :s

Cheers,

Alex

1
  • 3
    So, what exactly is the problem with cheating? ;-) Commented Feb 7, 2012 at 13:09

7 Answers 7

25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If you put the $isFirst = false; inside the first if it will skip setting the variable at every loop.
15

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);

3 Comments

As long as its not an associative array, or it's an indexed with first key of 0
I modified my initial post that provides a way for fetching the first element for other kinds of arrays.
It not work. 'foreach()' not move pointer of array. current() not show actual loop value.
6
$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;
}

Comments

3

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;

1 Comment

Using array_shift and foreach over the remaining array seems the cleanest solution, providing you are not using the array after looping through it. Otherwise you want to pop the first element back on with array_unshift.
1

You can just put the operation on first element before the foreach loop, remove the element and then enter the foreach loop for the rest of the elements.

Comments

1
$first = array_shift($idx);

foreach($idx as $key => $value){
...
...
...
}

Comments

0

Here are two functions that will detect if an array key is first or last.

If no key is provided it will assume the current pointer position.

In a foreach loop you will need to provide the key since the pointer will not be correct.

public static function isFirst($array, $key=null)
{
    if($key===null){
      $key = key($array);
    }
    reset($array);
    $first = key($array);
    return $first === $key;
}

public static function isLast($array, $key=null)
{
    if($key===null){
        $key = key($array);
    }
    end($array);
    $last = key($array);
    return $last === $key;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.