Menu

Add Topic

programming

waiting answer October 09, 2021

array_chunk in php

Answers
October 09, 2021

The array_chunk() function in PHP is an inbuilt function in PHP That is used to split an array into chunks (Parts) based on the parameters passed into the function.

Syntax

           array_chunk(Input Array, Size, Preserve keys);

  • In the Output, each chunk contains number of size elements.
  • Size defines the size of each chunk.
  • The Preserve keys is an Optional Parameter. By Default the value is FALSE. If the value is TRUE, then the keys are preserved.

Example 1:

       

              $input_array = array('Red', 'Blue', 'Green', 'Yellow', 'Violet');
              $chunk =    array_chunk($input_array, 2);
              print_r($chunk);

      ?>

Output

    Array
    (
        [0] => Array
            (
                [0] => Red
                [1] => Blue
            )

        [1] => Array
            (
                [0] => Green
                [1] => Yellow
            )

        [2] => Array
            (
                [0] => Violet
            )

    )    

If the preserve keys = TRUE, then the index of each element is same as the original element.

Example 2:

    <?php
        $input_array = array('Red', 'Blue', 'Green', 'Yellow', 'Violet');
        $chunk =    array_chunk($input_array, 2, true);
        print_r($
    ?>

Output:      

   Array
       (
           [0] => Array
               (
                   [0] => Red
                   [1] => Blue
               )

           [1] => Array
              (
                  [2] => Green
                  [3] => Yellow
             )

           [2] => Array
              (
                  [4] => Violet
             )

         )

0 0

Please Login to Post the answer

Leave an Answer