when to use array_chunk with examples ? in php

The array_chunk() function in PHP is used to split an array into chunks of smaller arrays. This can be useful when you want to process a large array in smaller parts, or when you want to display data in a paginated manner.

Here's an example to illustrate how to use array_chunk():

main.php
// Original array
$data = array('apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'kiwi');

// Split the original array into chunks of 3 elements each
$chunks = array_chunk($data, 3);

// Output each chunk
foreach ($chunks as $chunk) {
    print_r($chunk);
}
288 chars
11 lines

In this example, the original array will be split into chunks of 3 elements each. The output will be:

main.php
Array
(
    [0] => apple
    [1] => banana
    [2] => cherry
)
Array
(
    [0] => date
    [1] => elderberry
    [2] => fig
)
Array
(
    [0] => grape
    [1] => honeydew
    [2] => kiwi
)
189 chars
19 lines

This can be particularly useful when you want to paginate results or when you need to process large datasets in smaller, manageable parts.

related categories

gistlibby LogSnag