1

I've attempted many different ways to push an array into a multidimensional array, including array_push(), $array['index'] = $toPush but I keep being met with quite unexpected results. I have used both var_dump() and print_r() as detailed below in an attempt to debug, but cannot work out the issue.

My reasoning behind is to run a while loop to pull game id's and game names and store these in an assoc. array, and then push them into my main array.

$games_array = array 
(

    "games" => array 
     (
          array("id"=>"1", "game"=>"first game");
          array("id"=>"2", "game"=>"second game");
     )

);
// a while loop would run here and update $game_to_add;
$game_to_add = array("id"=>"$game['id']", "game"=>"$game['title']");

$games_array = array_push($games_array['games'], $game_to_add);

In this example, the while() would update the ID and the Game inside of $game_to_add

But, whenever I attempt this it simply overwrites the array and outputs an integer ( example: int(3) )

I don't understand what the problem is, any explination would be appreciated as I cannot find a question specifically for this.

My actual test code:

$games_array = array( "games" => array(
    array("id" => "1", "name" => "Star feathers"),
    array("id" => "2", "name" => "chung fu")
)
);

$another_game = array("id" => "3", "name" => "some kunt");
$games_array = array_push($games_array["games"], array("id" => "3", "name" 
=>"some game"));
var_dump($games_array);
4
  • Get rid of the $games_array assignment before array_push(). It modifies the array in place, it doesn't return it. Commented Nov 2, 2018 at 20:38
  • I can't believe I didn't notice that. I used Array_push() all over the shop, guess I was too close to the woods to see the trees. Thank you! Commented Nov 2, 2018 at 20:41
  • I suggest you get out of the habit of using array_push, and use the shorthand $arrayname[] = $new_value; Commented Nov 2, 2018 at 20:43
  • e.g. $games_array["games"][] = $another_game; Commented Nov 2, 2018 at 20:44

1 Answer 1

0

You're assigning the return value of array_push to the "games" array. The return value of array_push is the amount of elements after pushing.

Just use it as

array_push($array, $newElement);

(Without assignment)

If you're only pushing one element at the time, $array[] = $newElement is preferred to the prevent overhead of the function call of array_push

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.