Php 8.1-New Features | Array is a list? & Array Unpack

image from https://medium.com/geekculture/php-8-1-is-coming-and-it-already-promises-to-be-one-of-the-best-releases-a86da2ed953f

Today i want to write about new 2 features about array newly added in php 8.1. Array unpack method is added PHP in 7.4 version but we can only use this for integers. But now we can use that for all types of arrays. This is a good development for us.

Whats is Array Unpack and where we can use it?

Since PHP 7.4 we can use unpacking with spread operator. If you have javascript background or have interest to that you should know spread operator (…)from this language. Mainly it’s just 3 dots. And this combine an array to another one..

Before PHP 8.1 as i mentioned above we can use spread operator to merge arrays which has only integer keys. Array unpacking is effectively have same result with native array_merge method. With 8.1 we can use spread operator with string based keys and we do not get any fatal errors :)

Lets See Some Example

Before 8.1

Fatal error: Cannot unpack array with string keys in … on line …

As you can see if you wanna merge arrays with spread operator you only merge the arrays with integer keys. Otherwise you will get cannot unpack array with string keys fatal error.

With 8.1

Voila!!! There is no fatal error here.

As you can see above the spread operator (…) and array_merge is effectively same. You can use both of them to combine arrays.

Backwards Compatibility Impact

The array unpacking operator did not support string-keys prior to PHP 8.1, and resulted in a fatal error. Existing code that runs successfully on older versions should not cause any issues in PHP 8.1 or later.

array_merge results in identical results in all PHP versions. array_merge , and should be used on code that requires compatibility with PHP versions prior to 8.1.

Array_is_list Method

Determines if the given array is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to count($array)-1.

array_is_list method mainly check if array has keys begin from 0 and return boolean result of this operation. If you have some Python background you will remember what is list but let’s explain in short lists are arrays with all keys from 0 to count($array)-1.

Note:

This function returns true on empty arrays.

$notAList = [1 => "a", 2 => "b", 3 => "c"];

if the example above we don’t have 0 key that’s why it is not a list.

$list = [0 => "a", 1=> "b", 2=> "c"];

We can change example in this way to have a valid list.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store