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

前端 未结 11 598
说谎
说谎 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:22

    given what you need, $arr[0] is preferrable, because it's faster. array_shift is used in other situations.

    0 讨论(0)
  • 2021-01-14 04:24

    You would use $arr[ 0 ]; array_shift removes the first element from the array.

    EDIT


    This answer is actually somewhere between incomplete and plain out wrong but, because the comments of the two jon's I think that it should actually stay up so that others can see that discourse.

    The right answer:

    • reset is the method to return the first defined index of the array. Even in non-associative arrays, this may not be the 0 index.
    • array_shift will remove and return the value which is found at reset

    The OP made the assumption that $arr[0] is the first index is not accurate in that particular context.

    0 讨论(0)
  • 2021-01-14 04:24

    If you want the first element of an array, use $arr[0] form. Advantages - Simplicity, Readability and Maintainability. Keep things straight forward.

    Edit: Use index 0 only if you know that the array has default keys starting from 0.

    0 讨论(0)
  • 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]];
    
    0 讨论(0)
  • 2021-01-14 04:30

    array_shift will actually remove the specified value from the array. Do not use it unless you really want to reduce the array!

    See here: http://php.net/manual/en/function.array-shift.php

    0 讨论(0)
  • 2021-01-14 04:32

    with array_shif you have two operations:

    1. retrive the firs element
    2. shift the array

    if you access by index, actually you have only one operation.

    0 讨论(0)
提交回复
热议问题