PHP array_chunk() Function with Example

PHP array_chunk() Function

array_chunk() work is a cluster work, it is utilized to part a given exhibit in a number of the exhibit (pieces of exhibits).

Syntax:

    array_chunk(array_name, size, [preserve_keys]) : array

array_chunk(array_name, size, [preserve_keys]) : cluster

Here,

  • array_name is the primary cluster, which we need to change over into exhibit pieces.
  • size is the number of clusters to be changed over.
  • preserve_keys is a discretionary parameter and its default value is bogus. In the event that it is genuine keys will be safeguarded and in the event that it is “bogus” the keys of the exhibits will be re-filed in sub-clusters.

It restores a multidimensional exhibit.

Example:

    Input:
    $arr = array("Bilaspur", "Raipur", "Goa", "Bahatarai", "Kashmir");

    Output:
    Array
    (
        [0] => Array
            (
                [0] => Bilaspur
                [1] => Raipur
                [2] => Goa
            )

        [1] => Array
            (
                [0] => Bahatarai
                [1] => Kashmir
            )

    )

PHP Code 1:

<?php
	$arr = array("Bilaspur", "Raipur", "Goa", "Bahatarai", "Kashmir");
	print ("Original array is...\n");
	print_r ($arr);
	
	$arr1 = array_chunk($arr, 3);
	print ("array (size: 3) is...\n");
	print_r ($arr1);	
?>

Output:

Original array is...
Array
(
    [0] => Bilaspur
    [1] => Raipur
    [2] => Goa
    [3] => Bahatarai
    [4] => Kashmir
)
array (size: 2) is...
Array
(
    [0] => Array
        (
            [0] => Bilaspur
            [1] => Raipur
            [2] => Goa
        )

    [1] => Array
        (
            [0] => Bahatarai
            [1] => Kashmir
        )

)

PHP Code 2: with preserved – “true”

<?php
 $arr = array("Bilaspur", "Raipur", "Goa", "Bahatarai", "Kashmir");
 print ("Original array is...\n");
 print_r ($arr);
 
 $arr1 = array_chunk($arr, 3, true);
 print ("array (size: 2) is...\n");
 print_r ($arr1); 
?>

Output 2

Original array is...
Array
(
    [0] => Bilaspur
    [1] => Raipur
    [2] => Goa
    [3] => Bahatarai
    [4] => Kashmir
)
array (size: 2) is...
Array
(
    [0] => Array
        (
            [0] => Bilaspur
            [1] => Raipur
            [2] => Goa
        )

    [1] => Array
        (
            [3] => Bahatarai
            [4] => Kashmir
        )

)

See the output 1 and Output 2, in first output sub exhibits are re-recorded while in output 2 clusters are not re-listed.

Leave a Comment

error: Alert: Content is protected!!