The PHP array_chunk syntax would be like the below.
<?php
$array = array(
"Ahmed",
"Khaled",
"Mohamed",
"Tarek",
"Peter",
"Michael",
"Celinia",
"Dalida"
);
$chunked = array_chunk( $array, 3 );
print_r( $chunked ); // will show you 3 chunks per array
?>
The output:
Array ( [0] => Array ( [0] => Ahmed [1] => Khaled [2] => Mohamed ) [1] => Array ( [0] => Tarek [1] => Peter [2] => Michael ) [2] => Array ( [0] => Celinia [1] => Dalida ) )
The PHP array_chunk is a built-in function used to split the arrays into small arrays according to the needed size.
PHP array_chunk() Parameters
The array_chunk takes 3 parameters as the following:
- Array : required argument.
- Size: An integer value, refers to the number of elements for the new created arrays.
- Preserving the key: this is an optional, and it takes boolean value. This argument allows you to choose true or false according to the below.
- True: if you need to keep the same key of the old array
- False: to reset each array with a new index (the default option).
The basic syntax would be like the below.
array_chunk( ARRAY, SIZE, PRESERVE_ARRAY)
Let’s take examples.
Examples
In the following example, I will split the following array into 2 chunks.
<?php
$programming_languages = array(
"PHP",
"C++",
"Python",
"C#",
"C",
"JavaScript",
"Java",
"Prolog"
);
array_chunk( $programming_languages, 2 );
?>
This array_chunk( $programming_languages, 2 );
will reset the index for each chunked array. Because the third argument will be a false value by default. So the final output when you print this array would be like the below.
Array ( [0] => Array ( [0] => Ahmed [1] => Khaled [2] => Mohamed ) [1] => Array ( [0] => Tarek [1] => Peter [2] => Michael ) [2] => Array ( [0] => Celinia [1] => Dalida ) )
Check each child array, you will see each one started from 0 as index. But if you need to keep the same old indexes of the main array. You have to pass a true boolean value as a third argument like the below example.
<?php
array_chunk( $programming_languages, 2, true );
?>
When you print the array, would print the same following output:
Array ( [0] => Array ( [0] => PHP [1] => C++ ) [1] => Array ( [2] => Python [3] => C# ) [2] => Array ( [4] => C [5] => Javascript ) [3] => Array ( [6] => Java [7] => Prolog ) )
Wrapping Up
The PHP array_chunk is a built-in function used to split the arrays into small arrays according to the needed size. It takes 3 arguments as the below:
- Array
- Size of chunks
- Preserve Keys
The basic expression would be like the below one.
array_chunk( ARRAY, SIZE, PRESERVE_KEYS );
If you need more details, visit PHP manual.