phparrays

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


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

Solution

  • 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, intval($len / 2));
    $secondhalf = array_slice($input, intval($len / 2));
    

    The output from var_dump(): Demo

    array(2) {
      [0]=>
      string(1) "a"
      [1]=>
      string(1) "b"
    }
    array(3) {
      [0]=>
      string(1) "c"
      [1]=>
      string(1) "d"
      [2]=>
      string(1) "e"
    }