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. 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 )
Sign up to request clarification or add additional context in comments.

Comments

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';

Comments

4

Just add the new key.

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

Comments

4

You can add more elements by this way:

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

3 Comments

its working..thank u..how can we do same thing using array_push() ?
@vaishu you can't
@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)
4

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

Comments

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
)

Comments

2

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

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

Keys not found within the array will get created.

Comments

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);

Comments

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" ]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.