PHP - Grab the first element using a foreach

Viewed 85570

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?

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

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

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
  ?>

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.

Related