array_splice() is a native function call which will perform as needed. It can:
- Mutate the original array to contain the first half of the data set and
- Return the removed second half of the data set.
The advantage in using this technique is that fewer functions are called and fewer variable are declared. In other words, there will be economy in terms of memory and performance.
Assuming you don't know the length of your array, count() divided by 2 will be necessary. For scenarios where the array count is odd, typically programmers prefer that the larger half comes first. To ensure this, use a negative value as the starting position parameter of the splice call. Because array_splice() expects an integer, use the bitwise shift right operator with 1 to divide by two and truncate the result to an integer. In my snippet to follow, the count is 5, half is 2.5, and the negative starting position is 3 -- this means the final two elements (the elements at index 3 and 4) will be removed from the input array.
A demonstration:
$array = ["1", "2", "3", "4", "5"];
$removed = array_splice(
$array,
-(count($array) >> 1)
);
var_export([
'first half' => $array,
'second half' => $removed
]);
Output:
array (
'first half' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'second half' =>
array (
0 => '4',
1 => '5',
),
)
Notice that the second half array is conveniently re-indexed.
array_chunk() is certainly appropriate as well and offers some conveniences. Instead of calling ceil() to round up after dividing, you can just unconditionally add 1 to the count before using the bitwise shift right operator to divide by 2 and floor the result. Demo
var_export(
array_chunk($array, count($array) + 1 >> 1)
)