Home » Php » Initializing Multiple PHP Variables Simultaneously

Initializing Multiple PHP Variables Simultaneously

Posted by: admin November 29, 2017 Leave a comment


How may I initialize multiple PHP variables with a value of zero simultaneously without using an array? I wish to write code that is essentially equivalent to the following:

$first = 0;
$second = 0;
$third = 0;
$fourth = 0;
$first = $second = $third = $fourth = 0;


While it is feasible to initialize multiple variables using a comma operator within a for-loop, as follows:

for ($a=0,$b=0,$c=0,$d=0;;) {

(See demo here)

the list construct provides a more efficient way to perform multiple variable assignment, as depicted in the following example:


list( $first, $second, $third, $fourth ) = array( 0, 0, 0, 0 );
var_dump($first, $second, $third, $fourth );

See demo here

One may wish to reconsider avoiding the usage of arrays to achieve multiple initialized variables. With PHP7.1+ one may write simpler, robust code if one utilizes array destructuring available with short array syntax, as follows:


[$first, $second, $third, $fourth ] = [0, 0, 0, 0];
var_dump($first, $second, $third, $fourth );

See demo here.

If one needs to be certain that the variables being initialized were not previously set, see this related discussion, particularly this response.