(PHP 5 >= 5.4)
array_chunk_by
— Splits an array into chunks using a callback function.
array array_chunk_by( array $array, mixed $key1 [, mixed $... ] )
Chunks an array into arrays by iteratively applying the $callback function to the elements of the $array.
Based on Raivo Laanemets' groupAdjacent()
function.
-
$array
— The array to have chunking performed on. -
$callback
— The callback function to use.bool callback ( mixed $previous, mixed $current )
$previous
- Holds the value of the previous iteration.$current
- Holds the value of the current iteration.
If the
$callback
function returnsTRUE
, the the current value from$array
is split into a new chunk. -
$preserve_keys
— When set toTRUE
keys will be preserved. Default isFALSE
which will reindex the chunk numerically.
Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing related elements.
Example #1 array_chunk_by()
Splits the array where the difference between adjacent elements is greater than 1.
$input = [ 1, 2, 3, 4, 14, 21, 23, 28, 29 ];
$result = array_chunk_by( $input, function ($prev, $curr) {
return ($curr - $prev) > 1;
});
var_export( $result );
The above example will output:
array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
3 => 4,
),
1 =>
array (
0 => 14,
),
2 =>
array (
0 => 21,
),
3 =>
array (
0 => 23,
),
4 =>
array (
0 => 28,
1 => 29,
),
)
Example #2 array_chunk_by()
Groups the array where adjacent elements share the same value.
$input = [ 5, 5, 3, 5, 3, 3 ];
$result = array_chunk_by( $input, function ($prev, $curr) {
return ($previous != $current);
});
var_export( $result );
The above example will output:
array (
0 =>
array (
0 => 5,
1 => 5,
),
1 =>
array (
0 => 3,
),
2 =>
array (
0 => 5,
),
3 =>
array (
0 => 3,
1 => 3,
),
)
$ composer require mcaskill/php-array-chunk-by
Why are you not using Composer?
Download Function.Array-Group-By.php
from the gist and save the file into your project path somewhere.