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
  • 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,650
  • 2
  • 21
  • 31
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
  • 2,070
  • 6
  • 35
  • 54
4

Just add the new key.

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

You can add more elements by this way:

$array = array("a"=>"blue","b"=>"green");
$array['c'] = 'red';
Yupik
  • 4,932
  • 1
  • 12
  • 26
4

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

Sarkouille
  • 1,275
  • 9
  • 16
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,639
  • 1
  • 16
  • 25
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);
schellingerht
  • 5,726
  • 2
  • 28
  • 56
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
  • 38,771
  • 9
  • 70
  • 114