Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

variables

php

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();
like image 722
transformerTroy Avatar asked Dec 30 '11 15:12

transformerTroy


People also ask

Can you assign multiple variables at once?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

How assign multiple values to same variable in PHP?

PHP passes primitive types int, string, etc. by value and objects by reference by default. However, you CAN pass objects by value too, using keyword clone , but you will have to use parenthesis. $c = 1234; $a = $b = &$c; // no syntax error // $a is passed by value.

Can you assign multiple variables at once Java?

You can also assign multiple variables to one value: a = b = c = 5; This code will set c to 5 and then set b to the value of c and finally a to the value of b . One of the most common operations in Java is to assign a new value to a variable based on its current value.

How can I assign one variable to another variable in PHP?

PHP variables: Assigning by Reference PHP (from PHP4) offers another way to assign values to variables: assign by reference. This means that the new variable simply points the original variable. Changes to the new variable affect the original, and vice a verse.


5 Answers

Yes, you can.

$a = $b = $c = $d = array();
like image 161
Grim... Avatar answered Oct 15 '22 01:10

Grim...


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
[2] https://secure.php.net/manual/de/migration71.new-features.php#migration71.new-features.symmetric-array-destructuring

like image 43
d4rwel Avatar answered Oct 14 '22 23:10

d4rwel


$c = $b = $a;

is equivalent to

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

therefore:

$var1 = $var2 = $var3 = $var4=  $var5 = array();
like image 24
Miquel Avatar answered Oct 14 '22 23:10

Miquel


$var1 = $var2 = $var3 = $var4=  $var5 = array();
like image 22
Francois Avatar answered Oct 15 '22 01:10

Francois


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.

like image 34
Vernon Grant Avatar answered Oct 14 '22 23:10

Vernon Grant