Skip to content
Advertisement

PHP: How to split array into 2 parts?

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.

Any ideas on how I could do this? Thanks

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement