PHP Tutorial - 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
  $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.