How can i take an array, divide it by two and create two lists?
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);
Use array_chunk
to split the array up into multiple sub-arrays, and then loop over each.
To find out how large the chunks should be to divide the array in half, use ceil(count($array) / 2)
.
<?php
$input_array = array('a', 'b', 'c', 'd', 'e', 'f');
$arrays = array_chunk($input_array, 3);
foreach ($arrays as $array_num => $array) {
echo "Array $array_num:\n";
foreach ($array as $item_num => $item) {
echo " Item $item_num: $item\n";
}
}
Output
Array 0:
Item 0: a
Item 1: b
Item 2: c
Array 1:
Item 0: d
Item 1: e
Item 2: f
http://php.net/manual/en/function.array-slice.php
To slice the array into half, use floor(count($array)/2) to know your offset.
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);