Search

Laravel 5: Getting the First Element of an Array With head

April 11, 2018 —John Koster

The head is a simple wrapper around PHP's reset function. This function will return the first element of an array or false if the array is empty. This function does not modify the array.

#Signature

The signature of the head helper function is:

1function head(
2 $array
3);

#Example Use

Consider the following array:

1$sampleArray = [
2 'first',
3 'second',
4 'third'
5];

We can get the first element of the array (without removing it) like so:

1$firstElement = head($sampleArray);

The value of $firstElement would then be first. Additionally, the following function calls are equivalent:

1// Using the Laravel head function.
2$headValue = head($sampleArray);
3 
4// Using PHP's reset function.
5$resetValue = reset($sampleArray);

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.