Is it possible to de-structure an array in PHP equal to or similar to the list in Python?

4

In Python we can de-structure a list like this:

lista = [ "Maça", "Pera" ]
maca, pera = lista
print(maca, pera)

The output will be:

Maça Pera

I know that in PHP it is possible to get the result using the function list

$lista = [ "Maça", "Pera" ];
list($maca, $pera) = $lista;
echo "{$maca} {$pera}";

But I wonder if it is possible to get the result using the same notation or similar to Python?

    
asked by anonymous 07.11.2018 / 00:26

1 answer

7

No, it is not possible, PHP does not have the concept of tuples, so it is impossible in the same way. But this is not important, what matters is getting what you need. And let's face it, it's almost the same. As the inkeliz commented, it is possible to improve a bit using the direct list notation:

$lista = ["Maça", "Pera"];
[$maca, $pera] = $lista;
echo "{$maca} {$pera}";

See running on ideone . And no Coding Ground . Also put it on GitHub for future reference .

PHP has the idea that array solves everything, so it makes sense to be like this and not need new structures. Of course PHP is betraying its root and creating other forms, so it may be that one day it has tuple.

    
07.11.2018 / 00:44