46

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

9 Answers 9

105

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"
}
Sign up to request clarification or add additional context in comments.

4 Comments

Original poster wanted the extra element in the second half, but if you want the extra element in the first half, use round($len / 2) in both places where you have $len / 2.
@DustinGraham how about floor() in the first half and ceil() in the second? An array with 5 items will be split as following: 2 / 3
@Fleuv: An array with 5 items under your scenario would be split 1,2 and 4,5. The middle item would be left out. Coincidentally, that was just what I wanted, so thanks!
To ignore middle element, use round($len/2) in second half only.
19

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

1 Comment

Thanks for putting it in a foreach e.t.c although most guys are suggesting array_slice..
14

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

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

Comments

11

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

3 Comments

Hi @James Thank you for the solution, I came up with your solution and it's working fine but sometimes I'm getting Warning: array_chunk(): Size parameter expected to be greater than 0 my code line is list($array1, $array2) = array_chunk($myarray, ceil(count($myarray) / 2)); the code works fine and sometimes it will just throw that error, can you please tell me what could be the problem?
Hi @ZackTim sorry this answer is a long time later, so presumably it's no longer relevant. I assume that what's happening is that the array is empty? If so, you would need to do some kind of check to count that it has at least two elements in the array before it reaches this code, and handle it appropriately, e.g. setting $part1 = []; $part2 = [];
you have to cast it to int: list($part1, $part2) = array_chunk($array, (int) ceil(count($array) / 2));
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];
}

Comments

2

array_splice() is a native function call which will perform as needed. It can:

  1. Mutate the original array to contain the first half of the data set and
  2. Return the removed second half of the data set.

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 array_splice() expects an integer, use the bitwise shift right operator with 1 to divide by two and truncate the result to an integer. In my snippet to follow, the count is 5, half is 2.5, and the negative starting position is 3 -- this means the final two elements (the elements at index 3 and 4) will be removed from the input array.

A demonstration:

$array = ["1", "2", "3", "4", "5"];

$removed = array_splice(
    $array,
    -(count($array) >> 1)
);

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. Instead of calling ceil() to round up after dividing, you can just unconditionally add 1 to the count before using the bitwise shift right operator to divide by 2 and floor the result. Demo

var_export(
    array_chunk($array, count($array) + 1 >> 1)
)

Comments

1

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;

Comments

-1

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

Comments

-2

You can use laravel helper function.

$input = array("a", "b", "c", "d", "e", "f");
$collections = collect($input);
$chuncks = $collections->chuck(3) 
$chuncks->toArray(); // [["a", "b", "c"],["d", "e", "f"]]

souce:Array into chunks and results by chunks in a new line with php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.