Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP support array destructuring?

Tags:

php

I mean something like this:

$arr = ["1", "2", "3"];

$one;
$two;
$three;

$new = [$one, $two, $three] = $arr; 

As result I should get:

$one = 1;
$two = 2;
$three = 3;

I tried, it works in PHP 7.3.2:

var_dump($one); // returns 1
like image 730
OPV Avatar asked Feb 26 '19 20:02

OPV


People also ask

What is array Destructuring in PHP?

This language construct is used to "pull" variables out of an array. In other words: it will "destructure" the array into separate variables.

Does PHP have Destructuring?

Object Destructuring (PHP 7.1)Unfortunately there is no object destructuring. However you can convert an object to an associative array using get_object_vars , and then use associative array destructuring.

Can we Destructure array?

Destructuring in Arrays. To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]


1 Answers

Indeed, it is listed as a new feature in PHP 7.1:

The shorthand array syntax ([]) may now be used to destructure arrays for assignments (including within foreach), as an alternative to the existing list() syntax, which is still supported.

like image 111
trincot Avatar answered Sep 21 '22 06:09

trincot