Adam Mo.
Adam Mo.

Reputation: 772

Insert key and value into array

I have this code

$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
array_push($array, array('s' => 'six'));
print_r($array);

that insert new key and value into the array , but when i print the new $array it returned this

Array ( [o] => one [t] => three [f] => four [0] => Array ( [s] => six ) )

i need to return like this

Array ( [o] => one [t] => three [f] => four [s] => six )

how to remove [0] => Array () from the array ?

Upvotes: 2

Views: 5575

Answers (1)

Halcyon
Halcyon

Reputation: 57709

array_push is intended for lists.

$arr = array(5, 6, 7);
array_push($arr, 8); // array(5, 6, 7, 8);

You can add elements to arrays in many ways, this is one:

$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
$array["s"] = "six";

Here is another:

$array = array_merge($array, array("s" => "six"));

PHP treats lists like array(1, 2, 3); differently than associative arrays like array("foo" => "bar");. The differences are minor, but they show up with functions like array_push.

Upvotes: 5

Related Questions