Is it possible to unstructure an array in PHP equal to or similar to the Python list?

Asked

Viewed 891 times

7

In Python we can unstructure a list like this:

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

the exit 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 would like to know if it is possible to obtain the result using the same or similar Python notation?

  • 1

    I think the closest is to using the list, but you can use [$maca, $pera] = $lista, has the same behavior as list($maca, $pera) = $lista, but omits the list.

  • 1

    @Inkeliz I’m using the version 7.0.1 and I’m making the mistake: <b>Parse error</b>: syntax error, unexpected '=' in <b>[...][...]</b>

  • 1

1 answer

10


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 thing. As inkeliz commented it is possible to improve a bit using direct list notation:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

PHP has the idea that the 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 one day have tuple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.