Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign same value to multiple variables at once?

People also ask

Can we assign multiple values to multiple variables at a time?

We can assign values to multiple variables at once in a single statement in Swift. We need to wrap the variables inside a bracket and assign the values using the equal sign = . The values are also wrapped inside a bracket.

How do you assign the same value to multiple variables in typescript?

Put the varible in an array and Use a for Loop to assign the same value to multiple variables.

How do you assign multiple values to multiple variables in a single line declaration?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.

Is Python allows you to assign a single value to several variables simultaneously?

Python allows you to assign a single value to several variables simultaneously. Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively, and one string object with the value "john" is assigned to the variable c.


$var_a = $var_b = $same_var = $var_d = $some_var = 'A';

To add to the other answer.

$a = $b = $c = $d actually means $a = ( $b = ( $c = $d ) )

PHP passes primitive types int, string, etc. by value and objects by reference by default.

That means

$c = 1234;
$a = $b = $c;
$c = 5678;
//$a and $b = 1234; $c = 5678;

$c = new Object();
$c->property = 1234;
$a = $b = $c;
$c->property = 5678;
// $a,b,c->property = 5678 because they are all referenced to same variable

However, you CAN pass objects by value too, using keyword clone, but you will have to use parenthesis.

$c = new Object();
$c->property = 1234;
$a = clone ($b = clone $c);
$c->property = 5678;
// $a,b->property = 1234; c->property = 5678 because they are cloned

BUT, you CAN NOT pass primitive types by reference with keyword & using this method

$c = 1234;

$a = $b = &$c; // no syntax error
// $a is passed by value. $b is passed by reference of $c

$a = &$b = &$c; // syntax error

$a = &($b = &$c); // $b = &$c is okay. 
// but $a = &(...) is error because you can not pass by reference on value (you need variable)

// You will have to do manually
$b = &$c;
$a = &$b;
etc.