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

前端 未结 8 2116
梦毁少年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 01:58

    A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

    foreach($features as $key => $feature) {
        $features[$key]['new_key'] = 'new value';  
    } 
    


    Instead of this:

    foreach($features as $feature) {
        $feature['new_key'] = 'new value';  
    } 
    

    The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

    While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

提交回复
热议问题