first(), last() and pluck()

Grab items from an array or extract a column of values.

Syntax\Illuminate\Support\Arr::first($array, $callback, $default);

Arr::first() returns the first element that passes an optional truth test; Arr::last() does the same from the end. Arr::pluck() extracts a list of values for a given key — the same idea as the collection method.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A shipping calculator calls Arr::first() to retrieve the cheapest available courier from a sorted rates array based on a price threshold.
  • A feature-flag resolver uses Arr::first() to find the first matching rule in a priority-ordered list of flag conditions.
  • A fallback resolver uses Arr::last() to grab the most recent entry in a sorted log array when the latest event is needed.

More examples

Get the first element without a callback

Without a callback, Arr::first() and Arr::last() simply return the first and last element of the array.

Example · php
use Illuminate\Support\Arr;

$items = ['apple', 'banana', 'cherry'];

$first = Arr::first($items);          // 'apple'
$last  = Arr::last($items);           // 'cherry'

First item matching a condition

Passes a callback to Arr::first() to find the first shipping rate below a price threshold.

Example · php
use Illuminate\Support\Arr;

$rates = [
    ['carrier' => 'FedEx', 'price' => 12.50],
    ['carrier' => 'UPS',   'price' =>  9.99],
    ['carrier' => 'DHL',   'price' => 14.00],
];

$cheap = Arr::first($rates, fn($r) => $r['price'] < 10.00);
// => ['carrier' => 'UPS', 'price' => 9.99]

Default value when nothing matches

The third argument to Arr::first() is returned when no element satisfies the callback, preventing null from propagating.

Example · php
use Illuminate\Support\Arr;

$flags = ['beta_ui', 'new_checkout'];

$match = Arr::first(
    $flags,
    fn($f) => $f === 'dark_mode',
    'not_enabled'           // default value
);
// => 'not_enabled'

Discussion

  • Be the first to comment on this lesson.