46
$\begingroup$

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");
$\endgroup$
0

2 Answers 2

108
$\begingroup$

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));
$\endgroup$
Sign up to request clarification or add additional context in comments.

1 Comment

you have to cast it to int: $pieces = array_chunk($array, (int) ceil(count($array) / 2));
34
$\begingroup$

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);
$\endgroup$

2 Comments

Thanks, more appropriate to me since I needed my array to split at one specific index and not in more than 2 chunks
Heads up, I used array_splice by mistake instead of array_slice and got stuck wondering why the original array was changing!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.