2

I have an array value like below,

Array ( [0] => ["f","a","s","d"] [1] => ["d","b","a","c"] [2] => ["c"])

and also i want the array value like merged as below mentioned

Array ( [0] => ["f","a","s","d","d","b","a","c","c"])

The all key value should be merged under one new array key

KarnaGowtham
  • 95
  • 2
  • 14

5 Answers5

7

In the PHP 5.6 release you could do this with a better approach. PHP 5.6 added new functionality unpacking arrays called splat operater (…):

$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
$result = array_merge(...$arr);
Srikanth.K
  • 103
  • 7
3

You can pass your initial array as an argument to call_user_func_array and use array_merge:

$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
print_r(call_user_func_array('array_merge', $arr));

For php version which supports variadic arguments (since 5.6) it is simpler:

print_r(array_merge(...$arr));
u_mulder
  • 54,101
  • 5
  • 48
  • 64
  • I didn't know that `array_merge` is smart to know that it's only parameter is a nested array instead of multi parameters array style . thanks for the answer, but why didn't you just call the function `array_merge($arr)` without using `call_user_func_array` – Accountant م Jul 10 '17 at 09:13
  • `array_merge` merges arrays. If you pass one array to it - what should it merge this array __with__? – u_mulder Jul 10 '17 at 09:16
  • oh sorry, I misunderstood. I thought that you passed `$arr` as one parameter to `array_merge`. – Accountant م Jul 10 '17 at 09:34
3

Way 1:

$result = array_reduce($arr, 'array_merge', array());

Way 2:

$result = call_user_func_array('array_merge', $arr);

Way 3:

   foreach ($arr as $key => $value) {
      array_merge($result,$value);
   }

After getting result you have to do : for store as a string:

 $tmp[] = implode(",",$result);
  print_r($tmp);

 or as array:
 $tmp[] = result;
Parth Chavda
  • 1,819
  • 1
  • 23
  • 30
0

you can merge the arrays using array_merge http://php.net/manual/en/function.array-merge.php where you send in the array of arrays you have

rypskar
  • 2,012
  • 13
  • 13
0

with loop as you suggest.

$var = Array (["f","a","s","d"] ,["d","b","a","c"],["c"]) ;
$temp =[];
foreach ($var as $key => $value) {
   foreach ($value as $key_1 => $value_1) {
      array_push($temp, $value_1);
   }
}
print_r([$temp]);
Jees K Denny
  • 531
  • 5
  • 27