array_chunk() is an another PHP prebuilt / default array function, This function is basically allows user split an array into smaller chunks of new array or we can say if we need to create smaller array of a big array then we can use the array_chunk();
Syntax of array_chunk() :
array_chunk(array, length, preserve_key)
array (required) : It is the array for which we need to make the chunks or smaller array.
length (required) : The size of each chunk
preserve_key (optional) : true – Preserves the keys false – default. Reindexes the chunk numerically
Return Type / Values :
it returns a multidimensional numerically indexed array, starting with zero, with each dimension containing length elements.
Example 1 :
<?php $input_array = array('Rolex', 'Omega', 'Orpat', 'Tuder', 'Panerai'); print_r(array_chunk($input_array, 2)); print_r(array_chunk($input_array, 2, true)); ?>
Output will be :
Array ( [0] => Array ( [0] => Rolex [1] => Omega ) [1] => Array ( [0] => Orpat [1] => Tuder ) [2] => Array ( [0] => Panerai ) ) Array ( [0] => Array ( [0] => Rolex [1] => Omega ) [1] => Array ( [2] => Orpat [3] => Tuder ) [2] => Array ( [4] => Panerai ) )
Example 2 :
<?php $actual_age = array("Monu"=>"23","Sonu"=>"25","Parth"=>"10","Kanav"=>"4"); print_r(array_chunk($actual_age, 2, true)); ?>
Output will be:
Array ( [0] => Array ( [Monu] => 23 [Sonu] => 25 ) [1] => Array ( [Parth] => 10 [Kanav] => 4 ) )
Reference Article : https://www.php.net/manual/en/function.array-chunk.php
In the previous post I described regarding the PHP array_change_key_case Function
Hope this article helps you in PHP development and understandings of Array. Stay tuned for more PHP Tutorials, Hope you enjoyed reading, if you need the professional PHP, PHP Framework and Magento 2 Development we can help you, just Click on the Link and send me your requirements.