Wednesday, 24 September 2014

array_chunk in PHP

Using PHP array_chunk() function an array is divided into chunks of new arrays.
PHP Array chunk breaks an array into multidimensional array with existent array’s values.

Syntax:  array_chunk(array,size,preserve_key)

Parameters Description:
array : Required. Specifies the array  to use
size : Required. Specifies how many elements each new array will contain
preserve_key : Optional. Possible values:

  • true - Preserves the keys from the original array.
  • false - Default. Does not preserve the keys from the original array.
Example:
<?php
$days = array( "a"=>"Sunday","b"=>"Monday","c"=>"Tuesday","d"=>"Wednesday");
print_r( array_chunk($days,2) );
echo "<br />";
print_r(array_chunk($days,2,true) );
?>
Output:
Array (
           [0] => Array ( 
                                [0] => Sunday
                                [1] => Monday 
                              )
           [1] => Array (
                                [0] => Tuesday
                                [1] => Wednesday 
                              )
          )
Array ( 
          [0] => Array (
                               [a] => Sunday
                               [b] => Monday
                             ) 
          [1] => Array ( 
                               [c] => Tuesday
                               [d] => Wednesday 
                              ) 
         )

0 comments:

Post a Comment