Can you set multiple variables at once in PHP as you can using Java?

I want to create 5 variables of an array of types at once. Is it possible? In Java, I know that you can, but cannot find anything about PHP. I would like to do something like this:

$var1, $var2, $var3, $var4, $var5 = array(); 
+54
variables php
Dec 30 2018-11-12T00:
source share
5 answers

Yes, you can.

 $a = $b = $c = $d = array(); 
+95
Dec 30 '11 at 15:34
source share
โ€” -
 $c = $b = $a; 

equivalently

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

so:

 $var1 = $var2 = $var3 = $var4= $var5 = array(); 
+17
Dec 30 '11 at 15:36
source share
 $var1 = $var2 = $var3 = $var4= $var5 = array(); 
+9
Dec 30 '11 at 15:35
source share

Starting with PHP 7.1, you can use the syntax in square brackets :

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

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

+5
Oct. 31 '18 at 10:40
source share

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

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

See the documentation for more information.

+2
Jun 22 '18 at 8:43
source share



All Articles