Getting the first item of an array with PHP

Published on 2022-01-21 • Modified on 2022-01-21

In this snippet, we see how to get the first item of an array with PHP. This is a classic snippet every PHP developer had to use one day or another. In fact, there are multiple ways to do it; I won't show all of them but only one using the array_key_first() function. This function is not well known as it was introduced in PHP 7.3. Click on the "more on the web" or the StackOverflow links below to see all other methods.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet185Trait
{
    public function snippet185(): void
    {
        $myNicearray = [
            'foo' => 'first',
            'bar' => 'second',
            1 => 'before last',
            0 => 'last',
        ];

        echo $myNicearray[array_key_first($myNicearray)].PHP_EOL;

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!