-2

I have 2 arrays like so:

$array1 = array(
    array("foo"=>"bar","count"=>"3"),
    array("foo2"=>"bar2","count"=>"4"),
    array("foo3"=>"bar3","count"=>"2")
);

$array2 = array(
    array("foo4"=>"bar","count"=>"3"),
    array("foo5"=>"bar2","count"=>"4"),
    array("foo6"=>"bar3","count"=>"2")
);

how can i add the 3rd element of array2 into array1 so it can become like this:

$array1 = array(
    array("foo"=>"bar","count"=>"3"),
    array("foo2"=>"bar2","count"=>"4"),
    array("foo3"=>"bar3","count"=>"2"),
    array("foo6"=>"bar3","count"=>"2")
);

i have tried doing $array1 += $array2[2]; but it doesn't work. it just adds the keys from array("foo6"=>"bar3","count"=>"2") to array1 instead of adding it as an array in $array1

Could you help me out?

Niko
  • 26,516
  • 9
  • 93
  • 110
Krimson
  • 7,386
  • 11
  • 60
  • 97
  • 1
    google php arrays and have a good read through what you find. – Popnoodles Dec 13 '12 at 10:05
  • i don't get why my question is being down voted? – Krimson Dec 13 '12 at 10:07
  • ^ This question does not show any research effort – Popnoodles Dec 13 '12 at 10:08
  • how would a newbie know that its `$array1[] = $array2[2];` and not `$array1 = $array2[2];` ?? i have done my research and came across array_push() and array_merge(). It didn't work so i am asking here. – Krimson Dec 13 '12 at 10:08
  • It's the basics before you get to array_push and array_merge. Start from the beginning not the middle. Poking at it with a stick is not how to learn how something works. – Popnoodles Dec 13 '12 at 10:09

5 Answers5

4

The [] operator appends an element to the end of an array, like this

$array1[] = $array2[2];
dualed
  • 10,262
  • 1
  • 26
  • 29
4

Just do like this:

$array1[] = $array2[2];
moonwave99
  • 21,957
  • 3
  • 43
  • 64
2

If you want the exact 3rd item, then you could do something like:

$array1[] = $array2[2];

If you want the last item of the array, you can use:

$array1[] = $array2[count($array2)];
Oldskool
  • 34,211
  • 7
  • 53
  • 66
1

try this

$array1[] = $array2[2];
Sandy8086
  • 653
  • 1
  • 4
  • 14
0

array_merge() is a function in which you can copy one array to another in PHP. http://php.net/manual/en/function.array-merge.php

rOcKiNg RhO
  • 631
  • 1
  • 6
  • 16