Sunday, April 22, 2018

Is there any reason for using => instead of = in PHP when assign a value to array?

Answer


Answer




Please note that I have already read Reference — What does this symbol mean in PHP? and What Does This Mean in PHP -> or => and I know that what => do in PHP.



My question is different.



Generally most programming languages use = to assign value to another.




Example 01



$my_name = "I am the Most Stupid Person"; //Yes, that is my name in SO :-)



Example 02



$cars = array();

$cars[0] = "Volvo";
$cars[1] = "BMW";

$cars[2] = "Toyota";





Now let see following example.



$myArray = array(
0 => 'Big',
1 => 'Small',

2 => 'Up',
3 => 'Down'
);


Here is also what happen is we have assigned 'Big' for $myArray['0'].



But here we used => instead of =. Is there any special reason that PHP was designed that way?


Answer



Consistency of syntax is important, here I would say using => in arrays is to ensure = still works. For example:




$a = 5;


Sets the variable $a to 5.



$a = $b = 5;


Sets the variable $a and $b to 5. That is = as an operator assigns the right hand side to the left hand side (if possible) and its result is also the right hand side. So now, in the context of an array:




$a = array(
0 => 'foo'
);


Now $a[0] is 'foo'.



$a = array(
0 => $b = 'foo'

);


Now $a[0] and $b are both 'foo'. Now think about this:



$b = 0;
$a = array(
$b => 'foo'
);



Simply means $a[$b], that is, $a[0] is 'foo'. If PHP used = for array keys:



$b = 1;
$a = array(
$b = 'bar'
);


What is the value of $a? Is it [1 => 'bar']? Or is it [0 => 'bar']? Did $b get the value 'bar'? Or was it only used as a key?




As you can see, the parser would be very confusing this way, and there would be no way to allow keys defined by variables with this syntax.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...