Difference between “as $key => $value” and “as $value” in PHP foreach

前端 未结 8 2282
梦毁少年i
梦毁少年i 2021-01-30 01:21

I have a database call and I\'m trying to figure out what the $key => $value does in a foreach loop.

The reason I ask is because both these

8条回答
  •  忘掉有多难
    2021-01-30 02:08

    The difference is that on the

    foreach($featured as $key => $value){
     echo $value['name'];
    }
    

    you are able to manipulate the value of each iteration's $key from their key-value pair. Like @djiango answered, if you are not manipulating each value's $key, the result of the loop will be exactly the same as

    foreach($featured as $value) {
      echo $value['name']
    }
    

    Source: You can read it from the PHP Documentation:

    The first form loops over the array given by array_expression. On each iteration, the value >of the current element is assigned to $value and the internal array pointer is advanced by >one (so on the next iteration, you'll be looking at the next element).*

    The second form will additionally assign the current element's key to the $key variable on >each iteration.


    If the data you are manipulating is, say, arrays with custom keys, you could print them to screen like so:

    $array = ("name" => "Paul", "age" => 23);

    foreach($featured as $key => $value){
     echo $key . "->" . $value;
    }
    

    Should print:

    name->Paul

    age->23

    And you wouldn't be able to do that with a foreach($featured as $value) with the same ease. So consider the format above a convenient way to manipulate keys when needed.

    Cheers

提交回复
热议问题