Computer >> Computer tutorials >  >> Programming >> PHP

array_chunk() function in PHP


The array_chunk() function splits an array into chunks of arrays. It returns a multidimensional numerically indexed array, starting with zero.

Syntax

array_chunk(arr, chunk_size, preserve_key)

Parameters

  • arr − The array

  • chunk_size − The size of chunk in integer

  • preserve_key − It has the following values: TRUE- Keys are preserved, FALSE: The chunk is reindexed.

Return

The array_chunk() function returns a multidimensional numerically indexed array, starting with zero.

The following is an example that shows how an array is split.

Example

<?php
   $products = array("Electronics"=>"99","Accessories"=>"110","Clothing"=>"150","Furniture"=>"198");
   print_r(array_chunk($products,2,true));
?>

Output

Array
(
   [0] => Array
      (
         [Electronics] => 99
         [Accessories] => 110
      )

   [1] => Array
      (
         [Clothing] => 150
         [Furniture] => 198
      )
)