Does PHP have a peek array operation?

2019-06-24 15:21发布

I would like to peek at the first element of an array. This operation would be equivalent to this code:

function peek($list)
{
  $item = array_shift($list);
  array_unshift($list, $item);
  return $item;
}

This code just seems really heavy to me and peek is often provided by queue and stack libraries. Does php have an already built function or some more efficient way to do this? I searched php.net but was unable to find anything.

Additional note for clarity: The array is not necessarily numerically indexed. It is also possible the array may have had some items unset (in the case of a numerically indexed array) messing up the numerical ordering. It is not safe to assume $list[0] is the first element.

1条回答
We Are One
2楼-- · 2019-06-24 15:31

The current() function will give you the 'current' array-value. If you're not sure if your code has begun to iterate over the array, you can use reset() instead - but this will reset the iterator, which is a side-effect - which will also give you the first item. Like this:

$item = current($list);

or

$item = reset($list);

EDIT: the above two functions work with both associative and numeric arrays. Note: neither gives the 'key', just the 'value'. If you need the 'key' also, use the key() method to get the current 'key' (current refers to where the program is pointing in the array in the case of the array being iterated over - cf. foreach, for, iterators, etc.)

查看更多
登录 后发表回答