Array push with associate array
Asked Answered
B

4

20

If I am working with an associate array like such:

Array ( [Username] => user 
        [Email] => email 
      )

and I want to add an element to the end, I would think to do:

array_push($array, array('Password' => 'pass'));

However, this leaves me with:

Array ( [Username] => user 
        [Email] => email
        Array ( [Password] => pass )
      )

How can this be avoided so I end up with:

Array ( [Username] => user 
        [Email] => email
        [Password] => pass
      )

Much appreciated!

Brittan answered 7/7, 2011 at 23:1 Comment(0)
M
34

You are using an associative array so you just set the key/value pair like this.

$array["Password"] = pass;

I think you may need to review the difference between an array and an associative array. For example if I ran the same command again with a different value it would overwrite the old one:

$array["Password"] = "overwritten";

Giving you this

Array ( [Username] => user 
        [Email] => email
        [Password] => "overwritten"
      )

Which judging by your question is not what your expecting

Mekka answered 7/7, 2011 at 23:7 Comment(0)
G
14

Try out array_merge instead:

$array = array('Username' => 'user', 'Email' => 'email'); 
$array = array_merge($array, array('Password' => 'pass'));

This produces the array:

array('Username' => 'user', 'Email' => 'email', 'Password' => 'pass');
Griff answered 7/7, 2011 at 23:6 Comment(1)
You can also do this as a shortcut $array += array('Password' => 'test'); but be warned it won't override Password if already set. Also, I wouldn't personally do it. Just seemed like an addtional FYI.Exhaustive
H
4

Associative arrays aren't designed to have their keys in order. You can add an element via

$array['Password'] = 'pass';
Hillyer answered 7/7, 2011 at 23:5 Comment(0)
A
4

Generally, with an associative array you don't have control over the order of the elements.

The elements can be in any order.

However I've found php keeps the order that you add them.

So just do $myarra["name"] = "password"

Ackley answered 7/7, 2011 at 23:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.