Php 8.1-New Features | Array is a list? & Array Unpack
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?
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
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.
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.
Determines if the given
arrayis a list. An array is considered a list if its keys consist of consecutive numbers from
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
This function returns
trueon 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.