Backend Development

Understanding PHP 8 Array Unpacking

Understanding PHP 8 Array Unpacking

PHP 8 Array Unpacking. Array unpacking is a powerful feature in PHP that allows developers to expand arrays into individual elements. Introduced in PHP 7.4 and enhanced in later versions, it simplifies working with arrays by making code more readable and concise.

 

 

 

What Is Array Unpacking?

Array unpacking uses the spread operator (...) to extract elements from an array and insert them into another array or function call. In simple terms, it “unpacks” the contents of one array into another structure. 

This seems similar to Javascript spread operator where it can be used to merge array, objects and more.

 

Basic Syntax

$array1 = [1, 2, 3];
$array2 = [...$array1];

After unpacking:

$array2 = [1, 2, 3];

Combining Arrays

One of the most common uses of array unpacking is merging arrays.

$array1 = [1, 2];
$array2 = [3, 4];

$combined = [...$array1, ...$array2];

Result:

[1, 2, 3, 4]

This is cleaner than using array_merge().

 

Mixing Values and Arrays

You can also combine unpacked arrays with individual values:

$array = [2, 3];

$result = [1, ...$array, 4];

Result:

[1, 2, 3, 4]

 

Array Unpacking with Associative Arrays

Array unpacking with associative arrays added in PHP 8.1+ to allow support for non-numeric array keys.

$array1 = ["a" => 1];
$array2 = ["b" => 2];

$result = [...$array1, ...$array2];

Result:

["a" => 1, "b" => 2]

 

Key Overwriting

If keys overlap, later values overwrite earlier ones:

$array1 = ["a" => 1];
$array2 = ["a" => 2, "b" => 3, "c"=> 4];

$result = [...$array1, ...$array2];

Result:

["a" => 2, "b" => 3, "c" => 4]

Unpacking in Function Calls

Array unpacking is also useful when passing arguments to functions.

function add($a, $b, $c) {
    return $a + $b + $c;
}

$numbers = [1, 2, 3];

echo add(...$numbers);

When invoking a function using spread operator, the array values unpacked to become the function arguments.

Result:

6

Unpacking with nested arrays

$array1 = [
    [
        "a" => 1,
        "b" => 2
    ],
    [
        "c" => 3,
        "d" => 4
    ]
];

$array2 = [
    'sub' => [
        "e" => 5,
        "f" => 6
    ]
];

var_export([...$array1, ...$array2]);

Result:

array (
  0 => 
  array (
    'a' => 1,
    'b' => 2,
  ),
  1 => 
  array (
    'c' => 3,
    'd' => 4,
  ),
  'sub' => 
  array (
    'e' => 5,
    'f' => 6,
  ),
)

 

Advantages of Array Unpacking

  • Cleaner syntax compared to traditional methods like array_merge()
  • Improved readability
  • Flexible usage in arrays and function arguments
  • Better performance in some cases

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments