Arr::only() Method in Laravel 11.x & Laravel 12.x

In Laravel 11.x & Laravel 12.x, the `Arr::only()` method is a convenient utility provided by the `Illuminate\Support\Arr` class. This method allows you to extract a subset of key-value pairs from an array based on a specified list of keys.

Syntax:-

<?php
Arr::only(array $array, array|string $keys): array
?>

Parameters

`$array`: The array from which you want to extract the key-value pairs.
`$keys`: An array or a single string representing the keys you want to extract from the array.

Return Value

The method returns a new array containing only the key-value pairs from the original array that match the specified keys.

Example Usage

<?php
use Illuminate\Support\Arr;

$array = [
'name' => 'John',
'age' => 30,
'email' => 'john@example.com',
'city' => 'New York'
];

// Extract only the 'name' and 'email' keys
$result = Arr::only($array, ['name', 'email']);
print_r($result);
?>

Output

<?php
Array
(
[name] => John
[email] => john@example.com
)
?>

Explanation

1. The original array contains four key-value pairs.
2. The `Arr::only()` method is used to extract only the `name` and `email` keys from the array.
3. The resulting array contains only the specified keys and their corresponding values.

Additional Example with Single Key

You can also pass a single key as a string:

<?php
$result = Arr::only($array, 'name');
print_r($result);
?>

Output:-

<?php
Array
(
[name] => John
)
?>

This method is part of Laravel’s extensive collection of helper functions, which are designed to make working with arrays and other data structures more convenient and expressive.