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
Using a foreach loop you could do this:
$myarray = array("a", "b", "c", "d", "e", "f", "g");
$array1 = array();
$array2 = array();
$i = 1;
foreach ($myarray as $value) {
if ($i <= count($myarray) / 2) {
$array1[] = $value;
} else {
$array2[] = $value;
}
$i++;
}
But it's even easier to use array_splice
$myarray = array("a", "b", "c", "d", "e", "f", "g");
$array1 = array_splice($myarray, 0, floor(count($myarray)/2));
$array2 = $myarray;
Here's a one-liner which uses array_chunk:
list($part1, $part2) = array_chunk($array, ceil(count($array) / 2));
If you need to preserve keys, add true as the third argument:
list($part1, $part2) = array_chunk($array, ceil(count($array) / 2), true);
http://php.net/manual/en/function.array-slice.php
To slice the array into half, use floor(count($array)/2) to know your offset.
To get a part of an array, you can use array_slice:
$input = array("a", "b", "c", "d", "e");
$len = count($input);
$firsthalf = array_slice($input, 0, $len / 2);
$secondhalf = array_slice($input, $len / 2);
$limit=count($array);
$first_limit=$limit/2;
for($i=0;$i<$first; $i++)
{
echo $array[$i];
}
foreach ($i=$first; $i< $limit; $i++)
{
echo $array[$i];
}
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)