Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

php

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

like image 674
AlexMorley-Finch Avatar asked Feb 07 '12 13:02

AlexMorley-Finch


People also ask

How do you get the first value in foreach?

Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.

When we use foreach loop in PHP?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

What is array pointer in PHP?

In PHP, all arrays have an internal pointer. This internal pointer points to some element in that array which is called as the current element of the array. Usually, the next element at the beginning is the second inserted element in the array.


1 Answers

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.

like image 117
Choy Avatar answered Sep 22 '22 17:09

Choy