Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing Multiple PHP Variables Simultaneously

Tags:

php

People also ask

Can you initialize multiple variables at once?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

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.

Do you have to initialize variables in PHP?

PHP does not require it, but it is a good practice to always initialize your variables. If you don't initialize your variables with a default value, the PHP engine will do a type cast depending on how you are using the variable.


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

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

<?php
for ($a=0,$b=0,$c=0,$d=0;;) {
    break;
}
var_dump($a,$b,$c,$d);

(See demo here)

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

<?php

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:

<?php

[$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.


If you want to initialize multiple array variables then use

# Initialize multiple array variables with Empty values
$array_1 = $array_2 = $array_3 = array();

# Initialize multiple array variables with Some values in it
list( $array_1, $array_2, $array_3) = array('one','two','three');

# Print value of array variables
var_dump($array_1,$array_2,$array_3);

Output:
*******
string 'one' (length=3)
string 'two' (length=3)
string 'three' (length=5)

If you want to initialize multiple regular variables then use

# Initialize multiple regular variables with values
$a = $b = $c = 'Hello PHP';
echo $a.'<br>',$b.'<br>', $c.'<br>';

Output:
*******
Hello PHP
Hello PHP
Hello PHP