Friday 13 September 2019

Use of => in PHP

To elaborate a bit on what has already been said.


Assuming that you know about arrays in PHP. Which is really a way of grouping a "list" of items under the same variable given a certain index - normally a numeric integer index starting from 0. Say we want to make a list of the indexes English term, that is,


Zero
One
Two
Three
Four
Five

Representing this in PHP using an array could be done like so:


$numbers = array("Zero", "One", "Two", "Three", "Four", "Five");

Now, what if we wanted the reverse situation? Having "Zero" as key and 0 as value? Having a non-integer as a key of an array in PHP is called an associative array where each element is defined using the syntax of "key => value", so in our example:


$numbers = array("Zero" => 0, "One" => 1, "Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5);

The question now becomes: What if you want both the key and the value when using a foreach statement? Answer: the same syntax!


$numbers = array("Zero" => 0, "One" => 1, "Two" => 2, "Three" => 3, "Four" => 4, "Five" => 5);
foreach($numbers as $key => $value){
echo "$key has value: $value\n";
}

This would display


Zero has value: 0
One has value: 1
Two has value: 2
Three has value: 3
Four has value: 4
Five has value: 5

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...