1

Is there way to convert two dimentional array into single dimentional array without using foreach loop in php.

Below is the actual array

Array
(
    [0] => Array
        (
            [male] => male
            [female] => female
        )
    [1] => Array
        (
            [male] => male1
            [female] => female1
        )
)

And Output will be like

Array
(
    [0] = > male
    [1] = > female
    [2] = > male1
    [3] = > female1
)
Sarvan Kumar
  • 926
  • 1
  • 11
  • 27

2 Answers2

3

You can use reduce and use array_merge

$array = array( ... ); //Your array here
$result = array_reduce($array, function($c,$v){
    return array_merge(array_values($c),array_values($v));
}, array());

This will result to:

Array
(
    [0] => male
    [1] => female
    [2] => male1
    [3] => female1
)
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

This loops through your multidimensional array and stores the results in the new array variable $newArray.

$newArray = array();
foreach($multi as $array) {
 foreach($array as $k=>$v) {
  $newArray[$k] = $v;
 }
}
pedram shabani
  • 1,654
  • 2
  • 20
  • 30
  • While this code snippet might answer the question it is always better to add some explanation that might be useful to other readers too. – cezar Mar 15 '18 at 08:36