PHP - Function array_chunk()


Advertisements


Syntax

array array_chunk ( array $input, int $size [, bool $preserve_keys] );

Definition and Usage

Chunks an array into size large chunks. The last chunk may contain less than size elements.

Parameters

Sr.No Parameter & Description
1

input

The array to work on

2

size

The size of each chunk

3

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 size elements.

Example

Try out following example −

<?php
   $input_array = array('a', 'b', 'c', 'd', 'e');
   print_r(array_chunk($input_array, 2));
   print_r(array_chunk($input_array, 2, true));
?> 

This will produce following result −

Array (
   [0] => Array (
      [0] => a
      [1] => b
   )
   
   [1] => Array (
      [0] => c
      [1] => d
   )
   
   [2] => Array (
      [0] => e
   )
)

Array
(
   [0] => Array (
      [0] => a
      [1] => b
   )
   
   [1] => Array (
      [2] => c
      [3] => d
   )
   
   [2] => Array (
      [4] => e
   )
)

php_function_reference.htm

Advertisements