Home » Php » How to split/divide an array into 2 using php?

How to split/divide an array into 2 using php?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Help me to split or divide an array into 2 different arrays. Here is my single array

$array = array("1","2","3","4","5","6");

I want the above array into two array like below

$array1 = array("1","2","3");

$array2 = array("4","5","6");
How to&Answers:

Use array_chunk:

$pieces = array_chunk($array, ceil(count($array) / 2));

If you want them in separate variables (instead of a multi-dimensional array), use list:

list($array1, $array2) = array_chunk($array, ceil(count($array) / 2));

Answer:

array_slice works well as long as you know how many elements you want in each array:

$array1 = array_slice($array, 0, 3);
$array2 = array_slice($array, 3, 3);