CopyPastehas never been so tasty!

Divide array in chunks using array_chunk in PHP

by anonymous

  • 0
  • 0
  • 0
63 views

http://codingvilla.com/divide-array-in-chunks-using-array-chunk-php-single-article-683.aspx

Purpose:

 

The function array_chunk divide any array chunks of another array. It takes three parameters array_chunk(array,size,preserve_key). First parameter is original array, second is size of the chunks which specifies how many elements each new array will contain,, third parameter is optional if we pass it as true the index value/keys of the original array are kept in chunks. If we don’t pass it the default value is false and the index/keys of the original values are not kept.

 

 

Code:

 

1.    <?php

2.    $name=array("T"=>"Tahreem","R"=>"Rizwan",

         "A"=>"Anwar","M"=>"Misbah");

3.    print_r(array_chunk($name,2));

4.    echo "<br/>";

5.    ?>

 

 Output:

 

 

Array ( [0] => Array ( [0] => Tahreem [1] => Rizwan ) [1] => Array ( [0] => Anwar [1] => Misbah ) )

 

 

Explanation:

 

 

On line 2 we have declared an array $name and initialize it. Then pass it two array_chunk function of php that divide an array into parameter that we pass with array as you can see in the output.

 

Code:

 

1.    <?php

2.   $name=array("T"=>"Tahreem","R"=>"Rizwan","A"=>"Anwar","M"=>"Misbah");

3.    print_r(array_chunk($name,2,true));

4.    ?>

 

 

Output:

 

 

Array ( [0] => Array ( [T] => Tahreem [R] => Rizwan ) [1] => Array ( [A] => Anwar [M] => Misbah ) )

 

 

Explanation:

 

 

On line 2 we declare an array $name and initialize it. Then pass it two array_chunk function of php that divide an array into parameter that we have passed with array and third parameter is true to preserve the keys of the original array as you can see in the output. 

Add A Comment: