0

I have an array of two arrays that I am trying to merge into one array. My arrays are in a variable $arr, var_dump of which looks like this:

array (size=2)
  0 => 
    array (size=1)
      0 => string 'onetag' (length=6)
  1 => 
    array (size=1)
      0 => string 'anothertag' (length=10)

Applying $marr = array_merge($arr) doesn't appear to do anything. I am trying to get the merged array to look like this ['onetag', 'anothertag'], or upon var_dump like this:

array (size=2)
  0 => string 'onetag' (length=6)
  1 => string 'anothertag' (length=10)
Arthur Tarasov
  • 3,517
  • 9
  • 45
  • 57

3 Answers3

1

Try:

$marr = array_merge($arr[0],$arr[1]);
Noman Ghani
  • 468
  • 3
  • 9
  • Thanks, that works, but what if I do not know exactly how many arrays are in the `$arr` array? There can be from 1 to 10 or 20 arrays. I just used two as an example. How can I set it up then? – Arthur Tarasov May 12 '16 at 08:19
  • Just wrap it in a foreach loop and merge them consecutively. – Emanuel Oster May 12 '16 at 08:22
1

Use below code

$arr = array_column($arr,0);
var_dump($arr);

OUTPUT :

array (size=2)
  0 => string 'onetag' (length=6)
  1 => string 'anothertag' (length=10)
Brijal Savaliya
  • 1,101
  • 9
  • 19
1

array_merge takes at least two arrays as arguments and merge them into one. You are passing only one and no second to merge the first with. You want to create a single array with all the element of $arr[0] and $arr[1]. So you have tomerge $arr[0] and $arr[1] like so: array_merge($arr[0],$arr[1]);

And here is simple foreach loop:

$marr = array();
foreach ($arr as $key => $value) {
    $marr = array_merge($marr, $arr[$key]);
}
Pavel Petrov
  • 847
  • 10
  • 19