Search code examples
phpjsonarray-push

array_push with associative array results in a multidimentional array


I have the following function which does some stuff and returns an array:

function do_work($array){ 
      $result = array();

      array_push($result, array("HAHAHAH" => "looooooool"));

      foreach($array as $key=>$val){
          array_push($result, array($key => $val));
      }

      return $result;
}

I originally call this and pass the $_GET array in it. What I expect at the end is a flat JSON object. But this returns a JSON array instead:

in my calling code:

$array = do_work($_GET);
 echo json_encode($array);

if I give the function following GET array:

handler.php?action=register_new_user&shit=happens

This will be the result, but I want it to be a flat JSON not an array:

[{"HAHAHAH":"looooooool"},{"action":"register_new_user"},{"shit":"happens"}]

Solution

  • array_push pushes the contents onto the end of the array, and you're pushing an array onto the end of an array, meaning you're creating a multi dimensional array.

    If you want to merge two arrays, use array_merge or set the value directly if it's a single value:

    $foo = array('one' => 1, 'two' => 2);
    $bar = array('three' => 3, 'four' => 4);
    $foobar = array_merge($foo, $bar);
    
    // otherwise
    $foo['three'] = 3;