...

/

Warnings Promoted to Errors in Array Handling

Warnings Promoted to Errors in Array Handling

Learn about the warnings in arrays that are now considered errors in PHP 8.

A number of bad practices regarding arrays, allowed in PHP 7 and earlier versions, now throw an Error. As discussed in the previous lesson, PHP 8 array error-handling changes serve to give you a more forceful response to the error situations we describe here. The ultimate goal of these enhancements is to nudge developers toward good coding practices.

Here is a brief list of array-handling warnings promoted to errors:

  • Cannot add an element to the array as the next element is already occupied

  • Cannot unset the offset in a non-array variable

  • Only array and Traversable types can be unpacked

  • Illegal offset types

Let’s now examine each of the error conditions on this list, one by one.

Next element already occupied

In order to illustrate one possible scenario where the next array element cannot be assigned as it’s already occupied, have a look at this simple code example:

Press + to interact
<?php
// Cannot add element to the array as the next element is already occupied
$a[PHP_INT_MAX] = 'This is the end!';
// goes off the end of the array!
$a[] = 'Off the deep end';
var_dump($a);
?>

Assume that, for some reason, an assignment is made to an array element whose numeric key is the largest-sized integer possible (represented by the PHP_INT_MAX predefined constant). If we subsequently attempt to assign a value to the next element, we have a problem!

Here is the result of running this block of ...