开发者

how to use array_push when pushing both key and value in PHP

I have an empty array. I am able to push values using

array_push($list, item[0]);

But how do I push both key and value.

array_开发者_运维百科push($list[$key], $item[0])

this does not work.


$list['key']=$item[0];

should work.

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.


If you want to maintain the key => value pairs you could use array_merge function.

$arr1 = array('apple' => 'fruit', 'banana' => 'fruit');
$arr2 = array('turnip' => 'vegetable', 'mushroom' => 'other');

$newArray = array_merge($arr1,$arr2)

This will return:

Array
(
    [apple] => fruit
    [banana] => fruit
    [turnip] => vegetable
    [mushroom] => other
)

But if two keys are the same in two arrays the one in the first array will be overwritten by the value in the second.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜