In Laravel 11.x Laravel 12.x, the `Arr::partition()` method is a utility provided by the `Illuminate\Support\Arr` class. This method is used to split an array into two separate arrays based on a given condition or callback. One array will contain elements that satisfy the condition, and the other will contain elements that do not.
Syntax
<?php Arr::partition($array, $callback); ?>
Parameters
`$array`: The array you want to partition.
`$callback`: A callback function that determines the condition for partitioning. The callback should return `true` for elements that should go into the first array and `false` for elements that should go into the second array.
Return Value
The method returns an array containing two arrays:
1. The first array contains elements that satisfy the condition (where the callback returns `true`).
2. The second array contains elements that do not satisfy the condition (where the callback returns `false`).
Example Usage
Here’s an example of how you might use `Arr::partition()`:
<?php use Illuminate\Support\Arr; $array = [1, 2, 3, 4, 5, 6]; // Partition the array into even and odd numbers [$even, $odd] = Arr::partition($array, function ($value) { return $value % 2 === 0; }); // $even will contain [2, 4, 6] // $odd will contain [1, 3, 5] ?>
Explanation:-
1. The callback function checks if a number is even (`$value % 2 === 0`).
2. `Arr::partition()` splits the original array into two arrays:
– `$even`: Contains all even numbers.
– `$odd`: Contains all odd numbers.