In this tutorial, we’re going to see different possibilities to define several variables at once in PHP.
If you want to define several variables at once, a notation that is often expected would be to separate them with commas. In PHP this leads to a parse error.
<?php $a = 1, $b = 2; var_dump($a, $b); ?>
Parse error: syntax error, unexpected ',' in [...][...] on line 2
The easiest way to avoid this, is to use the semicolon instead of the comma. However, this no longer fulfills the condition “at once”, but only shows that commands in PHP do not have to be separated by line breaks.
<?php $a = 1; $b = 2; var_dump($a, $b); ?>
Use the following notation to assign multiple values to a single variable:
<?php $a = $b = $c = 1; var_dump($a, $b, $c); ?>
int(1) int(1) int(1)
The disadvantage of this notation is that the same value is always set for each of the variables.
Example : Assign multiple variables at once
With the combination of list() and an array, several variables can be assigned different values. However, this notation is more difficult to read and in order to assign the same value to several variables, it must be entered in the array as often as necessary.
<?php list($a, $b, $c) = array(1, 5, 2); var_dump($a, $b, $c); ?>
int(1) int(5) int(2)
It is also possible to “abuse” the for loop for assigning variables. To do this, just enter “false” in the right place, so that the loop never starts. The assigned variables are still present after the end of the loop – Unlike many other programming languages, in which they are lost at the end of the loop.
<?php for ($a = 1, $b = $c = 5; false;); var_dump($a, $b, $c); ?>
int(1) int(5) int(5)