tags:

views:

122

answers:

6
+2  Q: 

Use of => in PHP

What does this mean in PHP and when is the time to use it?

 =>

Another example.

 foreach ($parent as $task_id => $todo)
A: 

It has no meaning in PHP. "->" means accessing method or property of the class instance.

FractalizeR
Oh, but it does! :)
Pekka
Just outright wrong...
kastermester
See here: http://www.php.net/manual/en/language.operators.array.php
the_drow
OMG :) I never thought of arrays in this context ;) Lamer me ;)
FractalizeR
+8  A: 

It is used to create an associative array like this:

$arr = array( "name" => "value" );

And also in foreach loop like this:

foreach ($arr as $name => $value) {
   echo "My $name is $value";
}
Ramon
+6  A: 

You can use it working with arrays:

array ("key" => "value", "key" => "value")

... or in a foreach statement:

foreach ($my_array as $key => $value)
...
Pekka
A: 

It is used with associative arrays.

For example,

$gender = array('male'=>'M','female'=>'F');

Where $gender['male'] would give you 'M' and $gender['female'] will give you 'F'

aip.cd.aish
+1  A: 

=> is the array association operator, similar to the = assignment operator.

it is used mainly in array declarations of the form $arr = array( $key=>$value ) which is equivalent to $arr[$key] = $value, and of course, in the foreach control structure to assign values to key and value loop variables.

dar7yl
+3  A: 

Ok so to try and elaborate a bit on what has already been said.

Assuming that you know about array's 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, ie.

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, ie. "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 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: same syntax! (here \n means newline)

$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 print out:

Zero has value: 0

One has value: 1

Two has value: 2

Three has value: 3

Four has value: 4

Five has value: 5

Hope it helps and good luck learning more! :)

kastermester