Can you assign multiple variables at once in PHP like you can with Java?

PhpVariables

Php Problem Overview


I want to create 5 variables of type array all at once. Is this possible? In Java I know you can, but can't find anything about PHP. I'd like to do something like this:

$var1, $var2, $var3, $var4, $var5 = array();

Php Solutions


Solution 1 - Php

Yes, you can.

$a = $b = $c = $d = array();

Solution 2 - Php

Since PHP 7.1 you can use square bracket syntax:

[$var1, $var2, $var3, $var4, $var5] = array(1, 2, 3, 4, 5);

[1] https://wiki.php.net/rfc/short_list_syntax<br> [2] https://secure.php.net/manual/de/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring

Solution 3 - Php

$c = $b = $a;

is equivalent to

$b = $a;
$c = $b;

therefore:

$var1 = $var2 = $var3 = $var4=  $var5 = array();

Solution 4 - Php

$var1 = $var2 = $var3 = $var4=  $var5 = array();

Solution 5 - Php

I prefer to use the list function for this task. This is not really a function but a language construct, used to assign a list of variables in one operation.

list( $var1, $var2, $var3 ) = array('coffee', 'brown', 'caffeine');

For more information see the documentation.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontransformerTroyView Question on Stackoverflow
Solution 1 - PhpGrim...View Answer on Stackoverflow
Solution 2 - Phpd4rwelView Answer on Stackoverflow
Solution 3 - PhpMiquelView Answer on Stackoverflow
Solution 4 - PhpFrancoisView Answer on Stackoverflow
Solution 5 - PhpVernon GrantView Answer on Stackoverflow