user655334
user655334

Reputation: 1015

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

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

Upvotes: 8

Views: 14097

Answers (6)

Chris
Chris

Reputation: 4436

How about:

$array1; // your original array with all records
$array2 = array_splice($array1, ceil(count($array1)/2));

// or per your requirement of 1200 in the first array:
$array2 = array_splice($array1, 1200);

This just pops off the second half of elements from your original array and puts them in the second array. Not sure what the advantage of using array_slice twice like the other answers mention, unless you want 2 new arrays and don't want any elements removed from the original array.

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 613

I think array_chunk would be easier, especially as you don't need to know how many elements are in the array.

array array_chunk ( array $input , int $size [, bool $preserve_keys = false ] )

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
$size = ceil(count($input_array)/2));
print_r(array_chunk($input_array, $size));
print_r(array_chunk($input_array, $size, true));
?>

Upvotes: 7

nexus10242048
nexus10242048

Reputation: 131

$quantity = count($original_collection);

$collection1 = array_slice($original_collection, 0, intval($quantity / 2), true);
$collection2 = array_diff_key($original_collection, $collection1);

Upvotes: 13

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

$array1 = array_slice($input, 0, 1200);
$array2 = array_slice($input, 1200);

Upvotes: 5

rockerest
rockerest

Reputation: 10508

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.

Upvotes: 13

Shakti Singh
Shakti Singh

Reputation: 86406

$array1 = array_slice($array, 0, 1199);
$array2 = array_slice($array, 1200);

Upvotes: 7

Related Questions