Search code examples
phparraysflat

PHP flat array one dimension high and with empty values


I have this array $data:

Array
(
  [0] => Array
      (
          [0] => 1
      )

  [1] => Array
      (
      )

  [2] => Array
      (
      )

  [3] => Array
      (
          [0] => test@email.net
      )

)

There are always only one element in each array. So, how can i transform the $data array to this? I need the empty values too:

Array
(
  [0] => 1
  [1] =>
  [2] =>
  [3] => test@email.net
)

Solution

  • Use array_map:

    $arr = Array
    (
      [0] => Array
          (
              [0] => 1
          )
    
      [1] => Array
          (
          )
    
      [2] => Array
          (
          )
    
      [3] => Array
          (
              [0] => test@email.net
          )
    
    );
    
    function flaten($n)
    {
        if (isset($n[0])) {
           return $n[0];
        } else {
           return "";
        }
    }
    
    $resultArray = array_map(flaten, $arr);