Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would people use `$a = $b = 2;` in PHP?

Tags:

php

Why would people use this format? Whats different between this and $a=2; $b=2;?

like image 949
rickyduck Avatar asked Nov 30 '22 04:11

rickyduck


2 Answers

Not having to retype the 2. This is useful if the 2 changes to a 3 at some point.

like image 71
Dark Falcon Avatar answered Dec 01 '22 19:12

Dark Falcon


Functionally? nothing. They both do the same thing "set variables $a and $b to 2". But, it does communicate something to your fellow programmers and it is faster/easier in some circumstances. For example

for($i = $j = 0; $i < 5; $i++, $j--) echo "$i $j \n";

Outputs:

0 0
1 -1
2 -2
3 -3
4 -4

Of course, if you need $i and $j to initialize to something more useful, say, floor( count( $myArr ) / 2 ), it can also be useful that way.

Then there are other, similar uses:

$j = ( $i = 1 ) - 1; // $i = 1, $j = 0;
like image 27
cwallenpoole Avatar answered Dec 01 '22 19:12

cwallenpoole