multidimensional array to one dimensional array recursively

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error multidimensional array to one dimensional array recursively on this date .

I have this multidimensional array

$liste = [[1,2,3],5,[['x','y','z'],true]];

and I want to change it to one dimensionel array

$liste = [1,2,3,5,'x','y','z',true];

so i always have a problem that give me the same shape

function to_array($list){
    $out=[];
    if(!is_array($list)){
        return $list;
    }else{
        foreach($list as $line){
            $out[]= to_array($line);
        }
    }
    return $out;
}

where is the problem in this recursive function !!!

Answer

The issue with your code is that you are pushing the result of to_array into $out, when what you want to do is use array_merge. Now since that requires both parameters to be arrays, when $list is not an array, you need to return an array containing the individual value. So change these lines:

    return $list;
        $out[]= to_array($line);

To:

    return array($list);
        $out = array_merge(to_array($line));

i.e.

function to_array($list){
    $out=[];
    if(!is_array($list)){
        return array($list);
    }else{
        foreach($list as $line){
            $out = array_merge($out, to_array($line));
        }
    }
    return $out;
}

And you will get the result that you want:

var_export(to_array($liste));

Output:

array (
  0 => 1,
  1 => 2,
  2 => 3,
  3 => 5,
  4 => 'x',
  5 => 'y',
  6 => 'z',
  7 => true,
)