0

I am trying to make sense of the PHP docs for pushing a value to an existing array.

I want an array of object arrays. The nested arrays need to be accessed by the array key. I need to add objects one at a time. So if I go $array[123] I will get back an array of objects.

I have made this code to simulate what I am trying to do:

<?php

class Disc {
    public $name;
    public function __construct($name) {
        $this->name = $name;
    }
}

$discs = array();

$discs[123] = array();

$discs[123] = new Disc("blue");
$discs[123] = new Disc("red");

echo var_export($discs);

the docs seem to say that if I assign a value to array like this is should be same as array_push() but it doesn't seem to be the case.

What is right way to push objects into the array at the specified key?

1

1 Answer 1

0

Right now you're just reassigning $discs[123] to red from blue.

To Add to, add a new secondary key

$discs[123][0] = new Disc("blue");
$discs[123][1] = new Disc("red");

Creating a multidimensional array

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.