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

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

    If you have an associative Array you can also use reset($arr): It returns the first Element (doesn't remove), and sets the array pointer to this element.

    But the fastest way is $arr[0].

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

    Do you want to modify the arr array also? array_shift removes the first element of the array and returns it, thus the array has changed. $arr[0] merely gives you the first element.

    I would use $arr[0] unless I explicitly wanted to modify the array. You may add code later to use the arr array and forget that it was modified.

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

    $arr[0] only works if the array as numerical keys.

    array_shift removes the element from the array and it modifies the array itself.

    If you are not sure what the first key is , and you do not want to remove it from the array, you could use:

    <?php
    foreach($arr $k=>$v){
       $value = $v;
       break;
    }
    

    or even better:

    <?php
    reset($arr);
    $value = current($arr);
    
    0 讨论(0)
  • 2021-01-14 04:43

    If you don't want to change the array in question, use $arr[0] (which merely gets the first element), otherwise if you want to remove the first element of $arr from $arr, use array_shift($arr).

    For example:

    $arr=array(3,-6,2);
    $foo=$arr[0]; //$foo==3 and $arr==array(3,-6,2).
    $bar=array_shift($arr); //$bar==3 and $arr==array(-6,2).
    

    ETA: As others have pointed out, be sure that your array isn't an associative array (ie the keys are 0,1,...,(sizeof($arr)-1)), otherwise this probably won't work.

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

    Well, they do different things.

    • array_shift($arr) takes the first element out of the array, and gives it to you.

    • $arr[0] just gives it to you... if the array has numeric keys.

    An alternative that works for associative arrays too is reset($arr). This does move the array's internal pointer, but unless you're using those functions this is unlikely to affect you.

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