user3423927 user3423927 - 5 months ago 16
PHP Question

push element to 2D array in PHP

$peter=array('cs204'=>array(10,10,10));
$peter=array('cs366'=>array(7,8,9));

echo '<pre>';
print_r($peter);
echo '</pre>';


I am trying to insert values into an array $peter with course number(cs204,cs366) as keys. Instead of adding to second element to the array it is rewriting the data.
This is the current output(Actual):

Array
(
[cs366] => Array
(
[0] => 7
[1] => 8
[2] => 9
)

)


But I need this one as output(Expected):

Array
(
[cs204] => Array
(
[0] => 10
[1] => 10
[2] => 10
)

[cs366] => Array
(
[0] => 7
[1] => 8
[2] => 9
)

)


Please help me. I want to insert second element as:
$peter=array('cs366'=>array(7,8,9));

but not like this:
$peter['cs366']=array(7,8,9);

Oli Oli
Answer

Try this:

$peter=array('cs204'=>array(10,10,10));
$peter=array_merge($peter, array('cs366'=>array(7,8,9)));