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

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

    Let's say you have an associative array like this:

    $a = array(
        "one" => 1,
        "two" => 2,
        "three" => 3,
        "seventeen" => array('x'=>123)
    );
    

    In the first iteration : $key="one" and $value=1.

    Sometimes you need this key ,if you want only the value , you can avoid using it.

    In the last iteration : $key='seventeen' and $value = array('x'=>123) so to get value of the first element in this array value, you need a key, x in this case: $value['x'] =123.

提交回复
热议问题