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");
PHP: Split an array into chunksThe array_chunk() function is used to split an array into arrays with size elements. The last chunk may contain less than size elements. Specifies the array to split. If we set preserve_keys as TRUE, array_chunk function preserves the original array keys.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
#1 Using array_slice function to split PHP arrays array_slice() returns the sequence of elements from the array as specified by the offset and length parameters. $offset – The position in the array. $preserve_keys – Output the associative array with integer keys intact.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With