PHP - Grab the first element using a foreach
Even morer eleganterer:
foreach($array as $index => $value) {
if ($index == 0) {
echo $array[$index];
}
}
That example only works if you use PHP's built-in array append features/function or manually specify keys in proper numerical order.
Here's an approach that is not like the others listed here that should work via the natural order of any PHP array.
$first = array_shift($array);
//do stuff with $first
foreach($array as $elem) {
//do stuff with rest of array elements
}
array_unshift($array, $first); //return first element to top
You can simply add a counter to the start, like so:
$i = 0;
foreach($arr as $a){
if($i == 0) {
//do ze business
}
//the rest
$i++;
}
Yes, if you are not able to go through the object in a different way (a normal for loop), just use a conditional in this case:
$first = true;
foreach ( $obj as $value )
{
if ( $first )
{
// do something
$first = false;
}
else
{
// do something
}
// do something
}