first($array, callable $callback = null, $default = null)
Let's begin discussing the first helper method be examining the $callback. The $callback is a function that accepts a $key and a $value as its parameters. The following code sample is an anonymous function assigned to a variable named $isPostFormat. This function will use the Str::is helper method to check if a value is of the format /post/*:
1<?php
2
3use Illuminate\Support\Str;
4
5$isPostFormat = function($key, $value) {
6 return Str::is('/post/*', $value);
7};
If a given value satisfies the format, true is returned, otherwise false is returned.
This would return true:
1<?php
2
3$isPostFormat('key', '/post/array_first');
and this would return false:
1<?php
2
3$isPostFormat('key', 'not-a-post');
So how does this work with the first function? Consider the following array:
1<?php
2
3$sampleArray = [
4 'browser',
5 'headphones',
6 '/post/a-post-format',
7 'something else'
8];
We can call first function and pass our callback function as a parameter like so:
1<?php
2
3use Illuminate\Support\Arr;
4
5$firstPost = Arr::first($sampleArray, $isPostFormat);
The first function will iterate over every item in the array and apply our $callback function to each item. The first key/value pair to return true from the $callback function is returned as the value. Therefore, $firstPost would have the value of /post/a-post-format.
It is possible that no key/value pair will satisfy the callback function. To account for this, a $default value can be specified. The default value for the $default value is null. Consider the following array which has no valid post formats (according to our $isPostFormat function):
1<?php
2
3$sampleArray = [
4 'browser',
5 'headphones',
6 'not-a-post-format',
7 'something else'
8];
the same code from earlier would return null instead of /post/a-post-format:
1<?php
2
3use Illuminate\Support\Arr;
4
5$firstPost = Arr::first($sampleArray, $isPostFormat);
The default value can be changed by passing a third argument to the first function:
1<?php
2
3use Illuminate\Support\Arr;
4
5$firstPost = Arr::first($sampleArray, $isPostFormat, '/post/this-is-my-default-value');
The above code would return /post/this-is-my-default-value when no key/value pair satisfies the callback function.
#Optional $callback Parameter
The $callback function is an optional parameter, and can be omitted. When the $callback parameter is omitted, the first method will return the first item in the array:
1<?php
2
3use Illuminate\Support\Arr;
4
5// 'browser'
6$firstItem = Arr::first($sampleArray);
#array_first($array, $callback, $default = null)
The array_first function is a shortcut to calling Arr::first. This function is declared in the global namespace.
∎