Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array push with associate array

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!

like image 565
grep Avatar asked Jul 07 '11 23:07

grep


2 Answers

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

like image 128
Paul.s Avatar answered Oct 22 '22 21:10

Paul.s


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');
like image 14
brianreavis Avatar answered Oct 22 '22 21:10

brianreavis