Search code examples
phparraysarray-push

Add a key-value-entry to an array in PHP


i have some trouble working with arrays in PHP. The square breaket and the array_push methode does not work as expected. And even with all my imagination i can not figure out what is wrong with my way of thinking about arrays.

This is my code:

$users = array();
$users['4643'] = array("key1" => "value1");
$users['4643'] = array("key2" => "value2");
print_r($users);

Output:

Array
(
    [4643] => Array
        (
            [key2] => value2
        )

)

But i expected it to would look like this:

Array
(
    [4643] => Array
        (
            [key1] => value1
            [key2] => value2
        )

)

Even with array_push() - array_push($users['4643'], array("key2" => "value2")); - i can not add an other array to the $users['4643']-array (isn't this an array? PHP says so (" [4643] => Array ").

Please help me. I think there is something wrong with my idea of array, but even the beginer tutorials about arrays can not help me.


Solution

  • Your second assignment is overwriting the first array you added.

    Instead, set values in the array like this:

    $users['4643'] = array();
    $users['4643']["key1"] = "value1";
    $users['4643']["key2"] = "value2";