Sep 26, 2020 2 min read.
Array Destructuring: The Useful Feature PHP 7 I Have Never Used Before
Array destructuring is a new feature that was introduced on PHP 7.1. I have never thought that there was a feature like this till the time I write this post. It helps me a lot to produce readable and cleaner code.
If we familiar with Javascript’s ES6 may very well aware of this kind of destructuring feature which allows us to pull out data from arrays or objects into distinct variables. Using ES6 way, we can assign the top level properties of the objects to local variables using destructuring like below:
const strawHatPirates = {
name: 'Luffy D. Monkey',
devilFruit: 'Gomu Gomu no Mi'
}
const {name, devilFruit} = strawHatPirates
So, name
and devilFruit
has been assigned the variables from strawHatPirates
object respectively. This is one of the way how we achieved the object destructuring in Javascript. How about in PHP?
Speaking of which, for earlier PHP versions than 7.1, to assign the array values to variables you could using list()
like below:
list($whitebeard, $redHair, $bigMom, $beasts) = $pirates;
However from version 7.1, you can only use []
to achieve the same result:
[$whitebeard, $redHair, $bigMom, $beasts] = $pirates;
Let’s compare when we use the old way like when we want to extract email data. Here is the old way (probably only me who use this way, lol):
$email = 'hello@yefta.me';
$data = explode('@', $email, 2);
$local = $data[0]; // "hello"
$domain = $data[1]; // "yefta.me"
And here is the new way to make it more readable and cleaner:
$email = 'hello@yefta.me`;
[$local, $domain] = explode('@', $email, 2);
So, $local
will have hello
as well as $domain
will have yefta.me
.
We can also achieve it using list()
as already mentioned above, but using shorthand array syntax is way more cleaner and makes more sense.
Arghh, I think I should be more care about reading the change log of every technology stacks that I use.