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

前端 未结 8 2189
梦毁少年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:07

    Sample Array: Left ones are the keys, right one are my values

    $array = array(
            'key-1' => 'value-1', 
            'key-2' => 'value-2',
            'key-3' => 'value-3',
            );
    

    Example A: I want only the values of $array

    foreach($array as $value) {    
        echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'     
    }
    

    Example B: I want each value AND key of $array

    foreach($array as $key => $value) {                 
        echo $value; // Through $value I get first access to 'value-1' then 'value-2' and to 'value-3'  
    
        echo $key; // Through $key I get access to 'key-1' then 'key-2' and finally 'key-3'    
    
        echo $array[$key]; // Accessing the value through $key = Same output as echo $value;
        $array[$key] = $value + 1; // Exmaple usage of $key: Change the value by increasing it by 1            
    }
    

提交回复
热议问题