简体   繁体   中英

What does the => operator in the for-each loop mean?

I understand that => operator in PHP is used to assign values in an associative array:

$array = array(key1 => value1, key2 => value2, key3=> value3);

I understand that for-each loop in PHP is iterated like

foreach ($array as $value) {
  echo $value;
}

But I have encountered something like

foreach ($question->get_order($qa) as $value => $ansid) {...}

I do not understand the $value => $ansid part of it.

$question -> get_order($qa) returns an array. We want to iterate through it, so it should be foreach ($question -> get_order($qa) as $value) {...} ?

The => operator assigns the keys of the array to the variable on the left hand side, and the value to the variable on the right hand side. For example, if you array is

$array = array(key1 => value1, key2 => value2, key3=> value3);

then

foreach ($array as $key => $value) {
  echo "$key: $value\n";
}

will print

key1: value1
key2: value2
key3: value3

It is particularly useful if your array keys also have a meaning and you need them inside the for -loop, separate from the values.

For example:

$students_by_id = array( 1234 => "John Smith", 2372 => "Pete Johnson" );
$grades = array( 1234 => 87, 2372 => 68 );

foreach( $grades as $student_id => $grade ) {
  echo $students_by_id[$student_id] . " scored " . $grade . " / 100 points.\n";
}

Note that if the array is "not associative", eg

$array = array( value1, value2, value3 );

then PHP will create numeric indexes for you, and the $key variable in

foreach ($array as $key => $value )

will run through 0, 1, 2, 3, ..., making your loop effectively equivalent to

for ($key = 0, $key < count($array); ++$key) {
  $value = $array[$key];
  // ...
}

In general I would still recommend the => notation, if not for efficiency then at least in case indices go missing from the list or you decide to switch to an associative array after all.

In a for loop, you can use the same operator to get the keys as well as the values. The variable before => will get the key of each item, and the variable behind it will get its value.

So in your specific case, $value will get the key of the item ( 'key1' on the first iteration) and $ansid will get the value ( 'value1' on the first iteration).

This feature is particularly useful for arrays with (named) keys, but it will also work for normal arrays, in which case you get the numeric indices for the keys.

The $value => $ansid will return the key and the value, not just the value.

So if its a plain array, key would likely be 0,1,2,3,4 etc and value would be v0,v1,v2,v3,v4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM