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

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

    Say you have an array like this:

    $array = (0=>'123',1=>'abc','test'=>'hi there!')
    

    In your foreach loop, each loop would be:

    $key = 0, $value = '123'
    $key = 1, $value = 'abc'
    $key = 'test', $value = 'hi there!'
    

    It's great for those times when you need to know the array key.

提交回复
热议问题