Justin
Justin

Reputation: 131

PHP foreach loop example confusion

One of the examples of a foreach loop in PHP is

foreach ($row as $key => $value) { 
    // somecode
}

I am having trouble understanding what the => is doing. Can anyone run me through how it is "seen" or evaluated by PHP? What is the order of operation, what value is assigned to $key?

What makes it different from:

foreach ($row as $value) { 
    // somecode
}

?

I logically I thought that the value of $value would be assigned to $key, then it would be assigned as a row of $row, but that is obviously incorrect...

Upvotes: 13

Views: 12629

Answers (6)

CenterOrbit
CenterOrbit

Reputation: 6851

I understand it is a little tricky, I had problems understanding it when I first started using it. The more you use it, the more it makes more sense.

Your array would look like this:

//  "key"   "value"
//    |        |
//    V        V
$row['1'] = 'item1';
$row['2'] = 'item2';
$row['3'] = 'item3';
$row['4'] = 'item4';

Keys can be anything, they don't need to be numbers. That way you can iterate through all items in the array without needing to know the key!

So, your first example can be explained as follows:

//         +--- The ARRAY where all of your data is
//         |
//         |       +----- The KEY to access that element of the array
//         |       |
//         |       |        +----- The VALUE of that element
//         |       |        |
//         V       V        V
foreach ($row as $key => $value){
   if($row[$key] == $value){ // this statement is always true
      echo "true AGAIN!";  // and thus will always print this line
   }
}

As far as my understanding goes the => is not really an operand of sorts, it is just used to complete the structure of the foreach loop.

Upvotes: 22

daalbert
daalbert

Reputation: 1475

From the PHP Documentation:

For arrays, assigning a value to a named key is performed using the "=>" operator. The precedence of this operator is the same as other assignment operators.

This question also got me curious as to the name of the => operator in PHP.

As you can see the documentation does not explicitly give it a name. This lead me to scout PHP channels on IRC. The general consensus is that it is called a rocket operator.

Upvotes: 0

rid
rid

Reputation: 63442

Opcodes for foreach with key and value:

BCDF9C 0005: FE_RESET             (CV 0 ($array), u) -> VAR 2
BCE014 0005: FE_FETCH             (VAR 2, u) -> VAR 3
BCE08C 0005: OP_DATA              (u VAR 0 &(0+2208F38), u VAR 0 &(0+2208F38)) -> TMP_VAR 5 &(C8+2208F39)
BCE104 0005: ASSIGN               (CV 2 ($value), VAR 3) -> VAR 4
BCE17C 0005: ASSIGN               (CV 1 ($key), TMP_VAR 5) -> VAR 6
BCE1F4 0005: JMP                  (u &(BCDFA0+4))
BCE26C 0005: SWITCH_FREE          (VAR 2)

Opcodes for foreach with only value:

BCE2E4 0007: FE_RESET             (CV 0 ($array), u) -> VAR 7
BCE35C 0007: FE_FETCH             (VAR 7, u) -> VAR 8
BCE3D4 0007: OP_DATA              (u VAR 0 &(0+2208F38), u VAR 0 &(0+2208F38)) -> u VAR 0 &(0+2208F38)
BCE44C 0007: ASSIGN               (CV 2 ($value), VAR 8) -> VAR 9
BCE4C4 0007: JMP                  (u &(BCE2E8+B))
BCE53C 0007: SWITCH_FREE          (VAR 7)

Sorry for the strange opcode representation.

Basically, the version without key assigns two less variables per iteration. It doesn't assign the key and the temporary variable, but it simply assigns the var directly.

Upvotes: 0

Gazler
Gazler

Reputation: 84140

foreach ($row as $key => $value) { ..somecode..}

The above is used in an associative array, such as:

array("a" => 1, "b" => 2, "c" => 3);

In the above case, the $key variable is assigned the first value [a on the first iteration, b on the second, c on the final loop] (called the key) and the $value variable is assigned the second value [1 on the first iteration,2, on the second, 3 on the final] (called the value.)

If they key assignment was omitted then the $value would still be assigned the second value.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237817

PHP arrays are stored as pairs of keys and values:

$arr = array(
    'key1' => 'value1',
    'key2' => 'value2'
);

The standard foreach syntax gets just the values:

foreach ($arr as $value) {
    // value1, value2
}

The alternative syntax allows you to get keys as well:

foreach ($arr as $key => $value) {
    // $key is "key1", then "key2"
    // $value is "value1" then "value2"
}

See the manual entry for foreach.

Upvotes: 9

Nanne
Nanne

Reputation: 64399

The two examples are the same, but the first one adds a definition of the key that you are currently looking at, and names it $key.

Compare to an array() definition, like array('key' => 'value')

If you use the first method, you have $key containing 'key' and in the second example you don't.

Upvotes: 2

Related Questions