Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split the array in to two equal parts using php

Tags:

arrays

php

slice

how to split an array in to two equal parts using array_slice() in PHP ?

This is my requirement:

First array contains: 0-1200

Second array contains: 1200-end

like image 760
user655334 Avatar asked Apr 06 '11 05:04

user655334


2 Answers

From the documentation for array_slice, all you have to do is give array_slice an offset and a length.

In your case:

$firsthalf = array_slice($original, 0, 1200);
$secondhalf = array_slice($original, 1200);

In other words, this code is telling array_slice:

take the first 1200 records;
then, take all the records starting at index 1200;

Since index 1200 is item 1201, this should be what you need.

like image 83
rockerest Avatar answered Oct 10 '22 20:10

rockerest


$quantity = count($original_collection);

$collection1 = array_slice($original_collection, 0, intval($quantity / 2), true);
$collection2 = array_diff_key($original_collection, $collection1);
like image 42
nexus10242048 Avatar answered Oct 10 '22 20:10

nexus10242048