Hello there is an array of this type

Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) 

I want to divide into two arrays and get in this form

 Array( [0] => 1 [1] => 3 [2] => 5 ) 

and

 Array( [0] => 2 [1] => 4 [2] => 6 ) 

array_chunk () didn't help, suggest avriant?

    4 answers 4

    Odd left and even even right. We run through the array, check by modulo parity.

    A common part:

     $foo = array(1,2,3,4,5,6); $a = array(); $b = array(); 

    In the first case, we check the parity of the value:

     foreach ($foo as $v) { if ($v % 2 != 0) { $a[] = $v; continue; } $b[] = $v; } 

    Well, or check the parity / oddness of the key:

     foreach ($foo as $k=>$v) { if ($k % 2 != 0) $a[] = $v; else $b[] = $v; } 

    Variation of the cycle at your discretion.

    Another option:

     $cur = 'a'; while ($foo) { ${$cur}[] = array_shift($foo); $cur = ($cur == 'a') ? 'b' : 'a'; } 
    • And why in one case you have if / else, and in the other if / continue? I am not against the diversity in the code, just wondering. - VladD
    • one
      @VladD, just for a change. Somehow sad two times to write the same thing. - Denis Khvorostin
    • 2
      I wonder if php can do this: (($ k% 2! = 0)? $ A: $ b) [] = $ v; - VladD
    • @VladD, good idea. - Denis Khvorostin
    • OOO how many options :) Thank you - bemulima

    I would do it through array_walk() :

     $arr = explode(',','a,b,c,d'); $even = $odd = array(); array_walk( $arr, "oddity", array(&$even, &$odd)); function oddity( $value, $key, $result) { array_push($result[ $key & 1], $value); } 

    After completing:

     $arr = Array ( [0] => a [1] => b [2] => c [3] => d ) $even = Array ( [0] => a [1] => c ) $odd = Array ( [0] => b [1] => d ) 
    • And what is graceful. - VladD
    • one
      Generally class !!! - bemulima pm

    And why are you not comfortable with the simplest and most obvious way to run through the entire array and, depending on the parity / oddness of the current element, add it to either the first or the second array?

    I wouldn’t be surprised if php doesn’t have a built-in tool for such a splitting of arrays - yet you don’t have enough money for every sneeze. Moreover, as far as I know, PHP supports lambda functions; with their help, such operations are performed even simpler and shorter.

    ZY What you have shown is separation not by keys, but by values. Hmm .. and maybe the keys)

    • one
      @DreamChild: maybe by keys, values ​​with old keys 0, 2, 4 got into the new array and were reindexed there. - VladD
    • @VladD hmm .. agree)) - DreamChild
     // является нечетным function odd($var) { return($var & 1); } // является четным function even($var) { return(!($var & 1)); } $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5); $array2 = array(6, 7, 8, 9, 10, 11, 12); echo "Нечетные:\n"; print_r(array_filter($array1, "odd")); echo "Четные:\n"; print_r(array_filter($array2, "even"));