Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have a peek array operation?

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.

like image 994
danielson317 Avatar asked Mar 11 '15 15:03

danielson317


1 Answers

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

like image 154
David M Avatar answered Oct 03 '22 19:10

David M