Brief Explanation Of PHP Array Destructuring

Hello devs,

In this PHP array destructuring example tutorial, I will discuss what is PHP array destructuring and how it works. If you know javascript array destructuring then PHP array destructuring will be very clear to you.

PHP 7.1 released a new way of assigning the array’s elements to variables. It’s called array destructuring. In this example, I will show you many examples of PHP array destructuring like PHP associative array destructuring, PHP array destructuring default value, etc.

Let's see the example:

$person = ['Neymar','Junior'];
[$first_name, $last_name] = $person;

var_dump($first_name, $last_name)

 

Output
string(4) "Neymar"
string(3) "Junior"

 

You can skip also the arrays element in array destructuring like

$person = ['Neymar','Junior', 24];
[$first_name, , $age] = $person;

var_dump($first_name, $age);

 

Output
string(4) "Neymar"
int(24)

 

Let's see another example like swap variables using PHP array destructuring. We can swap variable without PHP array destructuring like

$x = 10;
$y = 20;

// swap variables
$tmp = $x;
$x = $y;
$y = $tmp;

var_dump($x, $y);

 

But we can do it in a very short way using PHP array destructuring like

$x = 10;
$y = 20;

// swap variables
[$x, $y] = [$y, $x];

var_dump($x, $y);

 

Recommended: How to Do Array Destructuring in JavaScript

 

Hope it can help you.

 

#php