PHP array_chunk: Split Arrays Easily

The array_chunk function is used to divide an array into several smaller arrays, with each smaller array containing a specified number of elements.

Syntax:
array_chunk(array, size, preserve_keys)

Parameters:

  1. array: the array that needs to be divided.
  2. Size: The number of elements included in each small array.
  3. preserve_keys: an optional parameter that specifies whether to keep the original keys of the array. By default, it is set to false, which means that the small arrays will be re-indexed.

Return value:
Return a two-dimensional array containing multiple subarrays.

I have to go to a meeting at 3 o’clock.

I need to attend a meeting at 3 p.m.

$fruits = array('apple', 'banana', 'orange', 'mango', 'strawberry', 'blueberry');
$chunks = array_chunk($fruits, 2);

print_r($chunks);

Result:

Array
(
    [0] => Array
        (
            [0] => apple
            [1] => banana
        )

    [1] => Array
        (
            [0] => orange
            [1] => mango
        )

    [2] => Array
        (
            [0] => strawberry
            [1] => blueberry
        )
)

In the example above, the original array is divided into 3 smaller arrays, each containing 2 elements.

bannerAds