0

I am just starting to understand how array_merge_recursive()works.

Can someone tell me how to use this php function with an array?

I am trying to do the following:

$ars[] = array("name_a" => array("color" => array("red")));
$ars[] = array("name_a" => array("color" => array("green", "blue")));
$ars[] = array("name_b" => array("color" => array("green", "tangerine")));
$ars[] = array("name_c" => array("color" => array("purple", "blue","red")));
$ars[] = array("name_c" => array("color" => array("green", "blue","green","beige")));
$ars[] = array("name_b" => array("color" => array("green", "blue","yellow")));

$result = array_merge_recursive($ars);

for some reason that I don't know, that does not work. The only way it is working for me is as follows:

$ars1 = array("name_a" => array("post_id" => array("red")));
$ars2 = array("name_a" => array("post_id" => array("green", "blue")));
$ars3 = array("name_b" => array("post_id" => array("green", "blue")));
$ars4 = array("name_c" => array("post_id" => array("green", "blue","red")));
$ars5 = array("name_c" => array("post_id" => array("green", "blue","green","beige")));
$ars6 = array("name_b" => array("post_id" => array("green", "blue","yellow")));
$result = array_merge_recursive($ars1,$ars2,$ars3,$ars4,$ars5,$ars6);

So, how can I put an array inside the array_merge_recursive(); function?

2
  • Quoting from the docs: array_merge_recursive — Merge __two or more arrays__ recursively (my emphasis).... you're trying to merge a single array..... explain what you're trying to achieve Commented Nov 27, 2014 at 23:19
  • At a guess: $result = call_user_func_array('array_merge_recursive', $ars); See demo Commented Nov 27, 2014 at 23:21

2 Answers 2

2

If you want to call array_merge_recursive(); or any other function with an array mapped as args you can use:

$result = call_user_func_array('array_merge_recursive', $ars);

Starting with PHP 5.6 there is a special operator for that:

$result = array_merge_recursive(...$ars);

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

Comments

0

I think you answered your own question didn't you?

array_merge_recursive() requires two parameters of array type so that you can "merge" them. what exactly are you merging with one array?

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.