How to declare PHP variables from the keys of an array


Is there any way to declare variables in php the same way we do in Javascript?

I would like to do this:

const { variavel1, variavel2, variavel3 } = array

To simplify this:

$variavel1 = $array['variavel1'];
$variavel2 = $array['variavel2'];
$variavel3 = $array['variavel3'];


Native resource: the list

This feature has been around since PHP 4, it's list() . It's that simple:

list($variavel1, $variavel2, $variavel3) = $array;

In newer PHPs it accepts this simplified syntax, but it's the same construct :

[$variavel1, $variavel2, $variavel] = $array;

Since PHP 7.1 you can choose items with indexes (be careful, it starts from 0):

list(1 => $variavel2, 2 => $variavel3) = $array;
[1 => $variavel2, 2 => $variavel3] = $array;

Or, omit variables that you don't need:

list( , $variavel2, $variavel3 ) = $array;


$array = [
list($variavel1, $variavel2, $variavel3) = $array;
echo "Var 1: $variavel1\n";
echo "Var 2: $variavel2\n";
echo "Var 3: $variavel3\n";


Var 1: UM
Var 2: DOIS
Var 3: TRES

See it working on IDEONE


Scroll to Top