In PHP, array_chunk is a commonly used array processing function. Its function is to cut a large array into multiple small arrays for easy processing. The basic usage of the function is as follows:
array_chunk(array $array, int $size, bool $preserve_keys = false): array
$array : The original array to be cut.
$size : The size of each small array.
$preserve_keys : Whether to preserve the key name of the original array.
When we pass in an empty array, what kind of behavior does array_chunk have? This is the focus of our discussion today.
If you are passing an empty array, array_chunk will return an empty array. Simply put, array_chunk([]) returns [] .
$result = array_chunk([], 2);
var_dump($result); // Output:array(0) { }
Even if the cut size ( $size ) is specified, the situation with an empty array will not be different. Regardless of whether the size you specify is 1, 2, or other values, the returned result is still an empty array.
$result = array_chunk([], 2);
var_dump($result); // Output:array(0) { }
$result = array_chunk([], 3);
var_dump($result); // Output:array(0) { }
Even if you set preserve_keys to true , the behavior of the empty array will not change, and the returned empty array is still the same.
$result = array_chunk([], 2, true);
var_dump($result); // Output:array(0) { }
array_chunk always returns an empty array when processing empty arrays, regardless of the size or preserve_keys you specify.
For empty arrays, the cut operation will not have any effect because there are no elements to split.
It should be noted that if you are passing a non-empty array and the elements in the array meet the cut requirements of the specified size, array_chunk will cut according to the rules, and if preserve_keys is set, it will retain the original key name. For example:
$array = [1, 2, 3, 4, 5];
$result = array_chunk($array, 2);
var_dump($result);
/* Output:
array(3) {
[0] => array(2) { [0] => 1, [1] => 2 }
[1] => array(2) { [0] => 3, [1] => 4 }
[2] => array(1) { [0] => 5 }
}
*/
In some practical development using array_chunk , it may involve arrays that need to process URL addresses. If you have a domain name in the URL (for example.com ), you can make sure that it always points to m66.net by replacing the domain name.
For example: