Desestruturando usando PHP
Recuperar itens de um array e já atribuir eles a variáveis.
// Array
$ colors = ['DC143C ' , '7FFFD4 ' , 'FFD700 ' ];
// Destructuring
list ($ crimson , $ aquamarine , $ gold ) = $ colors ;
// Testing values
print $ crimson . PHP_EOL ; // DC143C
print $ aquamarine . PHP_EOL ; // 7FFFD4
print $ gold . PHP_EOL ; // FFD700
Você pode ler mais a respeito do uso de list aqui:
https://www.php.net/manual/en/function.list.php
Você também pode usar a sintaxe shorthand e omitir o list durante a desestruturação.
// Array
$ colors = ['DC143C ' , '7FFFD4 ' , 'FFD700 ' ];
// Destructuring
[$ crimson , $ aquamarine , $ gold ] = $ colors ;
// Testing values
print $ crimson . PHP_EOL ; // DC143C
print $ aquamarine . PHP_EOL ; // 7FFFD4
print $ gold . PHP_EOL ; // FFD700
Esta é uma feature disponível a partir da versão 7.1 do PHP. Você pode ler mais a respeito aqui:
https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring
Trabalhando com arrays associativos
É possível efetuar desestruturação de arrays associativos também.
// Array
$ person = ['id ' => 15 , 'first_name ' => 'James ' , 'country ' => 'Australia ' ];
// Destructuring by associative array keys
['id ' => $ id , 'first_name ' => $ firstName , 'country ' => $ country ] = $ person ;
// Testing values
print $ id . PHP_EOL ; // 15
print $ firstName . PHP_EOL ; // James
print $ country . PHP_EOL ; // Australia
Esta é uma feature disponível a partir da versão 7.1 do PHP. Você pode ler mais a respeito aqui:
https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.support-for-keys-in-list