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
  • 916
  • 10
  • 26

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,040
  • 6
  • 32
  • 55
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,614
  • 2
  • 19
  • 28
  • 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