Get the first element of an array

后端 未结 30 2420
醉酒成梦
醉酒成梦 2020-11-22 10:59

I have an array:

array( 4 => \'apple\', 7 => \'orange\', 13 => \'plum\' )

I would like to get the first element of this array. Expect

30条回答
  •  深忆病人
    2020-11-22 11:37

    From Laravel's helpers:

    function head($array)
    {
        return reset($array);
    }
    

    The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, and it doesn't touch the original array (note it returns false if the array is empty).

    Usage example:

    $data = ['foo', 'bar', 'baz'];
    
    current($data); // foo
    next($data); // bar
    head($data); // foo
    next($data); // baz
    

    Also, here is an alternative. It's very marginally faster, but more interesting. It lets easily change the default value if the array is empty:

    function head($array, $default = null)
    {
        foreach ($array as $item) {
            return $item;
        }
        return $default;
    }
    

    For the record, here is another answer of mine, for the array's last element.

提交回复
热议问题