Does PHP have a peek array operation?

泪湿孤枕 提交于 2019-12-12 12:16:55

问题


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:


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.)



来源:https://stackoverflow.com/questions/28991041/does-php-have-a-peek-array-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!