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
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.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With