kirk bushell | Riding the wave of programmatic novelty

Retrieve the First Element of an Array

May 10, 2009 at 05:05 PM · Posted under Blog · Tagged with , ,

It's fairly general knowledge in PHP that if you want the first item of an array, you can use array_shift. However, this also removes the element from the array and this may not be the intended functionality of the developer. Introducing: array_first. array_first allows you to see the first element of an array, simply by passing the array. It can be a numerical or associative array, it just has to be an array.
function array_first($array)
{
  if (!is_array($array)) {
    throw new Exception('Argument is not an array.');
    return false;
  }
  $slice = array_slice($array, 0, 1);
  return $slice[0];
}
Updated the function to use array_slice() rather than finding the array keys, thanks Joe!

Comments

Craig Morris said @ May 11, 2009 @ 01:20 PM
reset($array); ???


Kirk Bushell said @ May 12, 2009 @ 04:43 PM
Absolutely Craig, but what if you're within a loop of that array?


Craig said @ May 13, 2009 @ 10:44 AM
Well, if you were using a foreach it wouldnt matter because foreach uses a copy of the original, so if you were resetting the original it wouldnt effect the loop.. ps.. why would you want the first element in a loop, you would get it before the loop surely!


Kirk Bushell said @ May 13, 2009 @ 01:51 PM
Craig - who knows! Perhaps person x is super tight on performance, and doesn't want to store an unnecessary variable? Reset would be my first bet whenever retrieving the first element, but I think it could lead to some unexpected results at times, hence writing this function.


Joe Beeson said @ May 16, 2009 @ 02:40 AM
array_slice($array, 0, 1)


Kirk Bushell said @ May 17, 2009 @ 10:04 AM
There you have it - cheers Joe =) Have updated the function to use that.


RSS feed for comments on this post

Leave a Comment