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
.
<?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 Snippet292Trait
{
public function snippet292(): void
{
$arr = [];
$arr[-4] = 'moins 4';
$arr[-3] = 'moins 3';
var_dump($arr);
$arr[] = 'moins 2';
var_dump($arr);
echo PHP_EOL;
$arr2 = [-4 => 'moins 4', 'moins 3'];
var_dump($arr2);
$arr2[] = 'moins 2';
var_dump($arr2);
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc More on the web Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
