PHP Array Function : array_chunk()

The array_chunk() function is used to splits an array into chunks of new arrays. In simple words it takes index or associative arrays and converts into multidimensional array. The syntax of the array_chunk() function is as follows :
 array_chunk(array, size, preserve__key);
Where array is the name of array you want to chunk or divide, size specifies the size of each chunk, and preserve_key is optional and its possible values are :

    true : Preserve the keys
    false : re-index the chunks numerically. And it is default one.

The array_chunk() function returns the multi-dimensional indexed array, starting with zero, with each dimension containing size elements.

Example :
<?php
  $my_arr = array("HTML", "CSS", "JavaScript", "PHP", "MySql", "JSP");

  $new_arr = array_chunk($my_arr, 3);
 
  // print the array as multidimentional array
  for($x = 0; $x < 2; $x++) {
    for($y = 0; $y < 3; $y++) {
      echo $new_arr[$x][$y] . "<br/>";
    }
  }
?>
Output :

HTML
CSS
JavaScript
PHP
MySql
JSP

Another example :
<?php
  $age = array("John"=> 25, "Sam" => 23, "Marry" => 30, "Luci" => 29, "Ronny" => 35);

  $new_arr = array_chunk($age, 2, true);
 
  // print the array as multidimentional array
  for($x = 0; $x < 2; $x++) {
    foreach($new_arr[$x] as $key => $value) {
      echo $key . " : " . $value . "<br/>";
    }
  }
?>
Output :

John : 25
Sam : 23
Marry : 30
Luci : 29


Next Topic :