PHP array_chunk() function splits array into chunks

Definition

The array_chunk() function splits an array into chunks and stores the chunks into new arrays.

Syntax

PHP array_chunk() function has the following syntax.

array_chunk(array,size,preserve_keys);

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to use
sizeRequired.Size of each chunk
preserve_keyOptional.If to preserve the key

Possible values for preserve_key:

  • true to preserve the keys
  • false(Default) to reindex the chunk numerically

Return

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

Example 1

Split an array into chunks of two.


<?php/* w  w  w  . java2  s. co m*/
  $letters=array("A","B","C","D","E","java2s.com");
  $split = array_chunk($letters,2); 
  print_r($split);
?>

The code above generates the following result.

Example 2

Split an array into chunks of two and preserve the original keys.


<?php
    $age=array("PHP"=>"5","Python"=>"7","Java"=>"3","java2s.com"=>"9");
    print_r(array_chunk($age,2,true));
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions