Function name: array_chunk php function.
There are few things which you need to keep in mind before start to understand this tutorial. You should have basic understanding of php arrays & print_r.
Syntax: array_chunk(array, size, preserved_keys)
Support: (PHP 4 >= 4.2.0, PHP 5, PHP 7)
Return Type: array_chunk php function will always return array.
- preserved_keys (optional)
Description about array_chunk php function:
With the help of this function you can divide or split your single array into multiple parts.
Array: It’s a collection of information, which we want to split into multiple parts.
Size: It’s an integer value. Whenever, we used array_chunk php function we always need to put the size of values in each generated array. For example: We have an array of having 5 values in it array(‘Seo’, ‘Designing’, ‘Development’, ‘Frameworks’, ‘JS’);
What if I want to split our above array into multiple parts. I want 2 values in each array which will generate after use of array_chunk php function. As I said , that this function will generate array at the end.So, our result will be an array and will have multiple arrays with in it. 2 values each array will occupy, so how many arrays will generate in our parent array? It will be 3. Why?
The reason is that we have 5 values in our above array right? So, divide these values in 2, 2 and the last one will be 1 because the remaining part will adjust as single value. Confused? Don’t worry we are performing some examples below.
Tip: Size value should be greater than 0, because on Zero it will throw an error.
Preserved_keys: Well, actually it is optional but it’s so useful. The values that pass through this third pareamter is bool (true or false). Check Example 1 and 2 below.
In this example we have an array of names, having list of 5 company members.
This example will show you that, how size and array_chunk php function works.
<?php $names = ['John', 'Rihana', 'Edward', 'Aliza', 'Guru']; $size = 2; echo('<pre>'); print_r(array_chunk($names, $size)); echo('</pre>'); ?>
Let’s do the same example but this time we are going to check what will be the impact of third parameter which is preserved_keys.
<?php $names = ['John', 'Rihana', 'Edward', 'Aliza', 'Guru']; $size = 2; $preserved_keys = true; echo('<pre>'); print_r(array_chunk($names, $size, $preserved_keys)); echo('</pre>'); ?>
Learn array_chunk php function from Video Tutorial below:
Don’t forget to tweet it & subscribe for more tutorials:Best Resource to learn PHP functions with in depth explanation. I just learned array_chunk within 1 minute from here Click To Tweet
Let me know if you’ll have issues in code in comments. I’ll wait for your feedback.
Don’t forget to share.
You will also like to learn array_change_key_case php function in 1 minute click here to learn this function.