Home » Php » php – How can i take an array, divide it by two and create two lists?

php – How can i take an array, divide it by two and create two lists?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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 has been counted and divided by two, with any remainder left in the second list?

So instead of just using the foreach to create one long list it will be creating two lists? like so…

  1. Value 1
  2. Value 2
  3. Value 3

and then the second list will continue to print in order

  1. Value 4
  2. Value 5
  3. Value 6
How to&Answers:

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);

Answer:

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

Answer:

http://php.net/manual/en/function.array-slice.php

To slice the array into half, use floor(count($array)/2) to know your offset.

Answer:

$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];
}

Answer:

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);

Answer:

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;

Answer:

This Worked for me made the first array always a little longer. Thought this might help people too.

$firsthalf = array_slice($input, 0, $len / 2 +1);
$secondhalf = array_slice($input, $len / 2 +1);