mcaskill/php-array-chunk-by

Splits an array into chunks using a callback function.

v1.0.0 2018-08-23 21:48 UTC

This package is not auto-updated.

Last update: 2024-12-12 22:50:01 UTC


README

(PHP 5 >= 5.4)
array_chunk_by — Splits an array into chunks using a callback function.

Description

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.

Parameters

  • $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 returns TRUE, the the current value from $array is split into a new chunk.

  • $preserve_keys — When set to TRUE keys will be preserved. Default is FALSE which will reindex the chunk numerically.

Return Values

Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing related elements.

Examples

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,
  ),
)

Installation

With Composer

$ composer require mcaskill/php-array-chunk-by

Without Composer

Why are you not using Composer?

Download Function.Array-Group-By.php from the gist and save the file into your project path somewhere.