PHP - Grab the first element using a foreach
Asked Answered
S

11

31

Wondering what would be a good method to get the first iteration on a foreach loop. I want to do something different on the first iteration.

Is a conditional our best option on these cases?

Sheff answered 18/10, 2010 at 9:12 Comment(0)
D
80

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
}
Discrown answered 18/10, 2010 at 9:16 Comment(5)
I had a "natural" first element, so I use that on the conditional. ;) But I really appreciate this idea. Thanks a lot.Sheff
its a cool trick ! but actually is there any function for this ?Imperious
No, you will have to use standard loop statements and then check for the first element somehow.Discrown
SMART! Love it.Discourse
It's so beautiful!Ginoginsberg
D
44

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
Dineen answered 18/10, 2010 at 9:36 Comment(1)
@NathanBell Technically all arrays are associative in PHP. This example only works if you use PHP's built-in array append features/function or manually specify keys in proper numerical order.Dineen
T
10

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++;
}
Thermotensile answered 18/10, 2010 at 9:14 Comment(0)
W
6

I saw this solution on a blog post in my search result set that brought up this post and I thought it was rather elegant. Though perhaps a bit heavy on processing.

foreach ($array as $element) 
{
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}

Do note there is also a warning on the post that this will only work if the array values are unique. If your last element is "world" and some random element in the middle is also "world" last element will execute twice.

Wiles answered 28/8, 2014 at 16:18 Comment(0)
M
5

hm

<?php
$i = 0;
foreach($ar as $sth) {
    if($i++ == 0) {
        // do something
    }
    // do something else
}

more elegant.

Marta answered 18/10, 2010 at 9:19 Comment(3)
Will this actually work? Will $i be really incremented after evaluation of the statement?Mutation
@yan Well, either the post-increment operator works as described, or PHP is terribly broken...Spiracle
yes. $i++ is evaluated after the expression, ++$i would be evaluated first.Marta
D
2
foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}
Democracy answered 18/10, 2010 at 9:12 Comment(1)
While this may answer the question it's better to add some description on how this answer may help to solve the issue. Please read How do I write a good answer to know more.Johannisberger
P
2
first = true
foreach(...)
    if first
        do stuff
        first = false
Pastose answered 18/10, 2010 at 9:15 Comment(0)
W
2

This is also works

foreach($array as $element) {
    if ($element === reset($array))
        echo 'FIRST ELEMENT!';

    if ($element === end($array))
        echo 'LAST ELEMENT!';
}
Waterhouse answered 23/8, 2017 at 11:4 Comment(0)
E
1

Here's an example that does not use foreach loop

 <?php
    // A sample indexed array
    $cities = array("London", "Paris", "New York");
    echo $cities[0]; // Outputs: London
     
    // A sample associative array
    $fruits = array("a" => "Apple", "b" => "Ball", "c" => "Cat");
    echo array_values($fruits)["0"]; // Outputs: Apple
  ?>
Electrostriction answered 31/12, 2020 at 10:37 Comment(0)
M
0

What about using key() native php function? which should work fine with all kind of arrays (indexed, associative ) as it will always return the first key no matter if its inside or outside the loop.

$array = array(
    'One'   => 'value',
    'Two'   => 'value-2',
    'Three' => 'value-3',
);

foreach ( $array as $index => $key ) {
    if ( key( $array ) ) {
        /**Do something with the first key*/
    } else {
        /**Do something else*/
    }
}

if it indexed array, you have many options you can go through, for me using counter is always fine and get the correct result all the time.

    $array = array(
        'One',
        'Two',
        'Three',
    );

    $i     = 0;
    foreach ( $array as $index => $key ) {
        if ( $array[ $i ] ) {
            /**Do something with the first key*/
        } else {
            /**Do something else*/

            $i++;
        }
    }

Both should work fine with $key => $value loop and it will only return the first key.

Also I would like to add something, You can always archive your target in scripting with hundreds of different way, Its all about the way you want to use in this situation.

Mernamero answered 31/12, 2020 at 17:10 Comment(0)
G
0

Your Query

$result = mysqli_query($conn, $sql) or die("Query failed!");
}

You'll get the first index row from your database

print_r(mysqli_fetch_assoc($result));
Grivation answered 27/3, 2023 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.