Page 1 of 1

array_push in associative array.

Posted: Wed May 30, 2007 5:29 pm
by Jorge
Hello all.

Is there any way I could use array_push to push new key-values in an associative array?
The following is pseudo-code of what I wish to achieve:

Code: Select all

$array = array('dog'  => 'The Dog', 'cat' => 'The Cat' );
array_push($array, 'mouse' => 'The Mouse');
If I can't use array_push to accomplish this then what can I use?

Cheers!

Posted: Wed May 30, 2007 5:33 pm
by s.dot
Maybe something like this, haven't tried it but it might work.

Code: Select all

$array = array('dog'  => 'The Dog', 'cat' => 'The Cat' ) + array('mouse' => 'The Mouse');
Edit: It does indeed work, if this is what you are after.

Code: Select all

C:\Users\HP_Administrator>php -r "$array = array('dog' => 'The Dog', 'cat' => 'T
he Cat') + array('mouse' => 'The Mouse');  print_r($array);
Array
(
    [dog] => The Dog
    [cat] => The Cat
    [mouse] => The Mouse
)

C:\Users\HP_Administrator>

Posted: Wed May 30, 2007 5:45 pm
by Jorge
Yes, thank you, that worked.

Posted: Wed May 30, 2007 5:45 pm
by Weirdan
or simply:

Code: Select all

$array = array('dog'  => 'The Dog', 'cat' => 'The Cat' );
$array['mouse'] = 'The Mouse';

Posted: Wed May 30, 2007 6:54 pm
by RobertGonzalez
I think weirdan's is faster, but I could be wrong.

Posted: Wed May 30, 2007 8:22 pm
by s.dot
Doing a primitive test out of boredom, it appears you're right, Everah.

Code: Select all

C:\Users\HP_Administrator>php -r "$start = microtime(true); for($i=0;$i<1000000;
$i++){ $array = array('dog' => 'The Dog', 'cat' => 'The Cat') + array('mouse' =>
 'The Mouse'); } $end = microtime(true);  echo $end-$start;"

2.1446731090546

C:\Users\HP_Administrator>php -r "$start = microtime(true); for($i=0;$i<1000000;
$i++){ $array = array('dog' => 'The Dog', 'cat' => 'The Cat'); $array['mouse'] =
 'The Mouse'; } $end = microtime(true); echo $end-$start;"

1.2985091209412

C:\Users\HP_Administrator>

Posted: Wed May 30, 2007 8:28 pm
by superdezign
Well, of course. It's an associative array. Weirdan's is faster and simpler, however, if that array element already exists, then it will just replace it.

No idea what your code would do in that case though.

Posted: Thu May 31, 2007 12:49 am
by Jorge
Thank you all, I opted for the second answer.