Using negative indices with PHP arrays

Published on 2024-02-24 • Modified on 2024-02-24

This snippet shows how to use negative indices with PHP arrays. It is one of the breaking changes introduced by PHP 8. If an array has an integer negative index, when adding an item with [], the new indices now take the following negative indices available instead of starting at 0. It is something to know, and it can break some applications. In the following example, with PHP 7.4 and before, the "moins 1" value indice would have been 0 instead of -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 Snippet292Trait
    public function snippet292(): void
        $arr = [];
        $arr[-4] = 'moins 4';
        $arr[-3] = 'moins 3';

        $arr[] = 'moins 2';

        echo PHP_EOL;

        $arr2 = [-4 => 'moins 4', 'moins 3'];
        $arr2[] = 'moins 2';

        // That's it! 😁

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

  Work with me!