Sunday, 22 April 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.
casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV
In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...
-
I'm using Simple HTML DOM to extract data from a HTML document, and I have a couple of issues that I need some help with. On the line th...
-
I've just started to learn CodeIgniter and gotten trouble with example below: My Controller: class Site extends CI_Controller ...
-
I am working with OpenSSL to try and get the SHA512 Hash function to work. When I am writing the code, Visual Studio's intellisense find...
No comments:
Post a Comment