Search code examples
phparrayslaraveleloquent

Split Eloquent result set into two equally-sized chunks


I have an array full of DB records. It could heaps of elements or very little, it changes regularly.

I need to split the array into two equal parts. The reason is I am then passing these arrays to a Laravel view and displaying them into separate columns.

Here is the DB records being pulled:

$books = Book::where('unitcode', '=', $unitcode['unitcode'])->get();

If the pull works then I'm running this:

return View::make('showbooks')
->with('books', $books);

What I want to do is pass $books1 and $books2 which is actually $books split into 2 parts.


Solution

  • This is a one liner:

    $halved = array_chunk($books, ceil(count($books)/2));
    

    Then $halved[0] will contain the first half of the array. It will always be 1 element larger in the event that the array contains an odd number of elements. Of course, $halved[1] will contain the 2nd half of the array.

    Here's a working example