Say i have an array
$array
Could anyone give me an example of how to use a foreach loop and print two lists after the initial array total
array_splice() is a single native function call which will perform as needed. It can:
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 the native function expects an integer (not a float), it will automatically truncate the value to form an integer -- this replaces the need to call an extra function (such as ceil() or floor()). In my snippet to follow, the count is 5, half is 2.5, and the negative truncated starting position is 2 -- this means the final two elements will be removed from the input array.
A demonstration:
$array = ["1", "2", "3", "4", "5"];
$removed = array_splice(
$array,
-count($array) / 2
);
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. To avoid the extra ceil() call, just unconditionally add .5 to the preferred chunk length.
array_chunk($array, count($array) / 2 + .5)