0

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.

2 Answers 2

4
$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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.