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
)
vaishu
  • 45
  • 1
  • 8

9 Answers9

7

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 )
Suneel Kumar
  • 1,634
  • 2
  • 22
  • 30
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';
Bhavin
  • 1,962
  • 5
  • 33
  • 49
3

Just add the new key.

$c["y"] = "yellow";
Nandan Bhat
  • 1,543
  • 2
  • 9
  • 21
3

You can add more elements by this way:

$array = array("a"=>"blue","b"=>"green");
$array['c'] = 'red';
Yupik
  • 4,794
  • 1
  • 10
  • 24
3

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

Sarkouille
  • 1,265
  • 9
  • 16
3

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);
schellingerht
  • 5,611
  • 2
  • 27
  • 52
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
)
Virb
  • 1,610
  • 1
  • 14
  • 24
2

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

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

Keys not found within the array will get created.

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" ]);
apokryfos
  • 34,925
  • 8
  • 65
  • 98