AppDividend
Latest Code Tutorials

PHP array_chunk Example | Array_chunk() Function Tutorial

0

PHP array_chunk() is an inbuilt function that splits the array into chunks of new arrays. The array_chunk() returns the multidimensional indexed array, starting with index zero, with each dimension containing size elements. I am using PHP version 7.2.14 for this example. The last chunk may contain less than size elements.

PHP array_chunk example

The syntax of array_chunk() function is following.

array_chunk(array,size,preserve_key);

An array parameter is required which specifies an array to use.

The size parameter is required which is an integer that specifies the size of the chunk.

The preserve_key parameter is optional. Possible values.

  1. true – Preserves the keys.
  2. false – Default. Reindexes the chunk numerically.

Let’s see the following example.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$netflix_chunk = array_chunk($netflix,2);
print_r($netflix_chunk);

See the below output.

PHP array_chunk Example

The output is multidimensional arrays in which each chunk contains two elements.

We can access those elements using the following way.

<?php

// app.php

$netflix = ['Stranger Things', 'Black Mirror', 'Bright', 'XOXO'];
$netflix_chunk = array_chunk($netflix,2);
echo $netflix_chunk[0][0]."\n";
echo $netflix_chunk[0][1]."\n";
echo $netflix_chunk[1][0]."\n";
echo $netflix_chunk[1][1]."\n";

See the below output.

array_chunk Function in PHP

Let’s take an example where we preserve the keys.

<?php

$data = array("Krunal"=>"26","Ankit"=>"25","Rushabh"=>"27");
print_r(array_chunk($data,2,true));

The output of the above code is following.

array_chunk Function Tutorial

In the above code, the third argument preserve key is passed as true therefore the index of elements in each chunk is the same as their index in the original array from which this chunk is created.

We can access the individual’s age using the following code.

<?php

// app.php

$data = array("Krunal"=>"26","Ankit"=>"25","Rushabh"=>"27");
$chunk = array_chunk($data,2,true);

echo $chunk[0]["Krunal"]."\n";
echo $chunk[0]["Ankit"]."\n";
echo $chunk[1]["Rushabh"]."\n";

The output is the following.

array_chunk Function Tutorial Example

Finally, PHP array_chunk Example | array_chunk Function Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.