It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Square bracket syntax for array destructuring assignment accepted

This is probably another great feature we're going to like in PHP 7.1. Since PHP 3 arrays have always been built with the array() syntax, in which we list its element by separating them with commas(;). And from PHP 5.4 it was possible to create an array with this $array = [] syntax.

As in PHP 3

<?php

// Creates an array containing elements with the values 1, 2 and 3, and keys numbered from zero
$array = array(1, 2, 3); 

// Creates an array containing elements with the values 1, 2 and 3, and the keys "a", "b", "c"
$array = array("a" => 1, "b" => 2, "c" => 3);

As in PHP 5.4

// Creates an array containing elements with the values 1, 2 and 3, and keys numbered from zero
$array = [1, 2, 3];

// Creates an array containing elements with the values 1, 2 and 3, and the keys "a", "b", "c"
$array = ["a" => 1, "b" => 2, "c" => 3];

This RFC mentioned one of the problems with the first syntax $array() is that it looks like a function call except the $ which makes the difference; Then the second option comes to eliminate that issue.

That is still a great way of constructing arrays. But what of destructing them, which is a way of assigning array elements to variables?

Since PHP 3 this was done by using the list() function in which we list the variables separated by commas like this:

<?php

// Assigns to $a, $b and $c the values of their respective array elements in $array with keys numbered from zero
list($a, $b, $c) = $array;

But in this case, the array must have numbered keys starting from zero, not for specific keys arrays, even though that has already been implemented in PHP 7.1. So this RFC suggested a cleaner way of destructuring arrays like the following:

Assigns to $a, $b and $c the values of their respective array elements in $array with keys numbered from zero:

[$a, $b, $c] = $array;

Assigns to $a, $b and $c the values of the array elements in $array with the keys "a", "b" and "c", respectively:

["a" => $a, "b" => $b, "c" => $c] = $array;

This is very awesome because it establishes a symmetric relation between the array construction and the destructuring.

Let's wait for the 7.1 release and test this feature.