PHP
Split PHP Array into Dynamic Chunks Using a Custom Callback
Learn to partition a PHP array into sub-arrays based on a flexible, user-defined callback function, enabling advanced and conditional data segmentation.
<?php
function splitArrayByCondition(array $array, callable $condition): array {
$chunks = [];
$currentChunk = [];
foreach ($array as $item) {
if ($condition($item) && !empty($currentChunk)) {
// If condition is met and current chunk is not empty, start a new chunk
$chunks[] = $currentChunk;
$currentChunk = [$item];
} else {
// Otherwise, add item to current chunk
$currentChunk[] = $item;
}
}
// Add the last chunk if it's not empty
if (!empty($currentChunk)) {
$chunks[] = $currentChunk;
}
return $chunks;
}
$logEntries = [
['timestamp' => '2023-01-01 10:00:00', 'event' => 'Login'],
['timestamp' => '2023-01-01 10:05:00', 'event' => 'Activity'],
['timestamp' => '2023-01-02 09:00:00', 'event' => 'Login'], // New day starts a new chunk
['timestamp' => '2023-01-02 09:30:00', 'event' => 'Activity'],
['timestamp' => '2023-01-02 10:00:00', 'event' => 'Logout'],
['timestamp' => '2023-01-03 11:00:00', 'event' => 'Login'] // New day
];
// Split log entries by day
$dailyChunks = splitArrayByCondition($logEntries, function($entry) {
static $prevDay = null;
$currentDay = (new DateTime($entry['timestamp']))->format('Y-m-d');
if ($prevDay === null) {
$prevDay = $currentDay;
return false; // First item doesn't start a new chunk
}
$isNewDay = ($currentDay !== $prevDay);
$prevDay = $currentDay;
return $isNewDay;
});
print_r($dailyChunks);
/* Expected output for $dailyChunks:
Array
(
[0] => Array
(
[0] => Array ('timestamp' => '2023-01-01 10:00:00', 'event' => 'Login')
[1] => Array ('timestamp' => '2023-01-01 10:05:00', 'event' => 'Activity')
)
[1] => Array
(
[0] => Array ('timestamp' => '2023-01-02 09:00:00', 'event' => 'Login')
[1] => Array ('timestamp' => '2023-01-02 09:30:00', 'event' => 'Activity')
[2] => Array ('timestamp' => '2023-01-02 10:00:00', 'event' => 'Logout')
)
[2] => Array
(
[0] => Array ('timestamp' => '2023-01-03 11:00:00', 'event' => 'Login')
)
)
*/
?>
How it works: This snippet provides a custom function `splitArrayByCondition` that partitions an array into sub-arrays based on a user-defined callback function. The callback receives each item and determines if it should mark the start of a new chunk. This is more flexible than `array_chunk` which splits by a fixed size, allowing for dynamic grouping of data, such as splitting log entries by day or transactions by a specific event type, offering granular control over array segmentation.