Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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"); 
like image 782
Aravinthan Avatar asked Jan 02 '13 01:01

Aravinthan


People also ask

How can I divide an array into two parts in PHP?

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.

How do you separate an array?

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.

How can I get array values and keys into separate arrays in PHP?

#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.


2 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)); 
like image 194
Joseph Silber Avatar answered Sep 19 '22 14:09

Joseph Silber


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); 
like image 43
Brad Christie Avatar answered Sep 16 '22 14:09

Brad Christie