Declaring PHP variables from the keys of an array

Asked

Viewed 98 times

4

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

I’d like to do that:

const { variavel1, variavel2, variavel3 } = array

To simplify this:

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

3 answers

8

Native resource: the list

This feature exists since PHP 4, is the list(). It’s that simple:

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

In newer Phps it accepts this simplified syntax, but it is the same Construct:

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

Since PHP 7.1 you can choose the items with indexes (beware, starts from 0):

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

Or omit variables you don’t need:

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

Example:

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

Upshot:

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

See working on IDEONE

Handbook:
https://www.php.net/manual/en/function.list.php

4

You can do this way for associative arrays:

$array = [
    'a' => 1,
    'b' => 2,
    'c' => 3,
];
['c' => $c, 'a' => $a] = $array;

Or in the case of a list:

$array = [1, 2, 3];
[$a, $b, $c] = $array;

Using your example we would have something like this:

['variavel1' => $variavel1, 'variavel2' => $variavel2, 'variavel3' => $variavel3] = $array

OBS: The destructuring array is available as of PHP version 7.1

0

  • 2

    It was not I who gave -1 but the problem of extract is that the programmer has no control over the variables created, whereas in the other responses with destructuring and list this does not happen. Still pointing out what the doc says: Warning Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES).

Browser other questions tagged

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