PHP
Partitioning an Array into Sub-Arrays Based on a Callback
Discover how to segment a PHP array dynamically into multiple sub-arrays using a custom callback function, useful for complex data partitioning based on conditions.
<?php
function array_partition(array $array, callable $callback): array
{
$partitions = [];
$currentPartitionKey = null;
foreach ($array as $key => $value) {
$newPartitionKey = call_user_func($callback, $value, $key);
if ($newPartitionKey !== $currentPartitionKey) {
$currentPartitionKey = $newPartitionKey;
$partitions[$currentPartitionKey] = [];
}
$partitions[$currentPartitionKey][] = $value;
}
return $partitions;
}
$transactions = [
['id' => 1, 'date' => '2023-01-10', 'amount' => 100],
['id' => 2, 'date' => '2023-01-15', 'amount' => 50],
['id' => 3, 'date' => '2023-02-01', 'amount' => 200],
['id' => 4, 'date' => '2023-02-05', 'amount' => 75],
['id' => 5, 'date' => '2023-03-20', 'amount' => 120],
['id' => 6, 'date' => '2023-03-25', 'amount' => 300],
];
// Partition transactions by month
$transactionsByMonth = array_partition($transactions, function($transaction) {
return substr($transaction['date'], 0, 7); // 'YYYY-MM'
});
// var_dump($transactionsByMonth);
/* Expected $transactionsByMonth (simplified):
[
'2023-01' => [
['id' => 1, 'date' => '2023-01-10', 'amount' => 100],
['id' => 2, 'date' => '2023-01-15', 'amount' => 50],
],
'2023-02' => [
['id' => 3, 'date' => '2023-02-01', 'amount' => 200],
['id' => 4, 'date' => '2023-02-05', 'amount' => 75],
],
'2023-03' => [
['id' => 5, 'date' => '2023-03-20', 'amount' => 120],
['id' => 6, 'date' => '2023-03-25', 'amount' => 300],
],
]
*/
How it works: This `array_partition` function allows you to split a single array into multiple sub-arrays based on a custom callback function. The callback determines the 'key' for each partition. When the value returned by the callback changes for an element, a new partition is started. This is incredibly useful for segmenting data streams or lists of items where the partitioning logic is more complex than a fixed size, enabling dynamic grouping based on any condition you define.