Handling Arrays in PHP 8
Learn how to handle arrays effectively with the new updates introduced in PHP 8.
We'll cover the following
Aside from improvements in performance, the two main changes in PHP 8 array handling pertain to the handling of negative offsets and curly brace ({}
) usage. Since both of these changes could result in application code breaks following a PHP 8 migration, it’s important to cover them here. Awareness of the issues presented here gives us a better chance to get broken code working again in short order.
Let’s have a look at negative array offset handling first.
Dealing with negative offsets
When assigning a value to an array in PHP, if we do not specify an index, PHP will automatically assign one for us. The index chosen in this manner is an integer that represents a value one higher than the highest currently assigned integer key. If no integer index key has yet been assigned, the automatic index assignment algorithm starts at zero.
In PHP 7 and below, however, this algorithm is not applied consistently in the case of a negative integer index. If a numeric array starts with a negative number for its index, auto-indexing jumps to zero (0
) regardless of what the next number would ordinarily be. In PHP 8, on the other hand, automatic indexing consistently increments by a value of +1
regardless of whether the index is a negative or positive integer.
A possible backwards-compatible code break is present if our code relies upon auto-indexing and any of the starting indexes are negative numbers. Detection of this issue is difficult as auto-indexing occurs silently, without any Warnings
or Notices
.
The following code example illustrates the difference in behavior between PHP 7 and PHP 8. Here is the code running in PHP 7.
Get hands-on with 1400+ tech skills courses.