Arrays: array_shift($arr) or $arr[0]?

前端 未结 11 735
说谎
说谎 2021-01-14 04:08

Which one would you use?

Basically I only want to get the 1st element from a array, that\'s it.

11条回答
  •  清歌不尽
    2021-01-14 04:27

    arrshift is more reliable and will always return the first element in the array, but this also modifies the array by removing that element.

    arr[0] will fail if your array doesn't start at the 0 index, but leaves the array itself alone.

    A more convoluted but reliable method is:

    $keys = array_keys($arr);
    $first = $arr[$keys[0]];
    

提交回复
热议问题