2
$c=array("a"=>"blue","b"=>"green");
array_push($c,$c["d"]="red");
print_r($c);

this code adding the key in to an array. But it also adding the indexed key to same key/value pair..how to avoid this indexed key? output:

Array
(
    [a] => blue
    [b] => green
    [d] => red
    [0] => red
)
2
  • 8
    array_push doesn't make any sense on associative arrays, only indexed arrays.
    – GordonM
    Commented Jul 20, 2017 at 12:16
  • wondering why the question is downvoted! it's clear and shows a try with code Commented Jul 20, 2017 at 12:22

9 Answers 9

8

Just add another key value like this

$c=array("a"=>"blue","b"=>"green");
$c["d"]="red";
print_r($c);

Out put is

Array ( [a] => blue [b] => green [d] => red )
5

Don't use array_push() here it's not necessary. Just add new key with value.

$c= array("a"=>"blue","b"=>"green");
$c['d'] = 'red';
4

Just add the new key.

$c["y"] = "yellow";
4

You can add more elements by this way:

$array = array("a"=>"blue","b"=>"green");
$array['c'] = 'red';
3
  • its working..thank u..how can we do same thing using array_push() ?
    – vaishu
    Commented Jul 20, 2017 at 12:19
  • @vaishu you can't
    – apokryfos
    Commented Jul 20, 2017 at 12:19
  • @vaishu You can't, array_push is for non-indexed arrays (and should be used to add multiple values, for single values it's better to use it in this way)
    – Yupik
    Commented Jul 20, 2017 at 12:21
4

Have you tried to simply use $c['d'] = 'red'; ?

0
2

Do it like by,

$c=array("a"=>"blue","b"=>"green");
$c["d"]="red";
echo "<pre>";
print_r($c);

and Output like,

Array
(
    [a] => blue
    [b] => green
    [d] => red
)
2

Push the new key-value pair into the array like so:

$c["d"] = "red";

Keys not found within the array will get created.

2

In addition to the others: you can push elements to the array, but there's no documented way (http://php.net/array_push) to choose your own keys. So array_push uses numeric index by itself.

A possible alternative for associative array is using an (anonymous) object (stdClass). In that case you can set properties and it's a little bit more OOP style of coding.

$foo = new stdClass;
$foo->bar = 1;

var_dump($foo);

// if you really want to use it as array, you can cast it
var_dump((array) $foo);
1

array_push is basically an operation which treats an array as a stack. Stacks don't have keys, so using an associative array with array_push does not make sense (since you wouldn't be able to retrieve the key with array_pop anyway).

If you want to simulate the behaviour of array_push which allows the simultaneous addition of multiple entries you can do the following:

$c = array_merge($c, [ "d" => "red", "e" => "some other colour" ]);

Not the answer you're looking for? Browse other questions tagged or ask your own question.