2

So consider an array with my 3 favorite fruits:

$array1 = array("Apple", "Banana","Raspberry")

I want to merge it with their own beautiful and natural color

$array2 = array("Green ", "Yellow ","Red ")

So that the results would look like

([0] => Green Apple [1] => Yellow Banane [2] => Red Raspberry) 

I need something to be scalable (2 to 6 keys, always the same between arrays)

What I tried and results

  • array_combine($array2,$array1)

    Result: Array ( [Green ] => Apple [Yellow ] => Banana [Red ] => Raspberry )

  • array_merge($array2,$array1)
    Result: Array ( [0] => Green [1] => Yellow [2] => Red [3] => Apple [4] => Banana [5] => Raspberry )

  • array_merge_recursive($array2,$array1)
    Result: Array ( [0] => Green [1] => Yellow [2] => Red [3] => Apple [4] => Banana [5] => Raspberry )

2 Answers 2

2

You actually should loop through arrays to combine them.

$combinedArray = array();
foreach ( $array1 as $key=>$value ) {
    $combinedArray[$key] = $array2[$key] . ' ' . $array1[$key];
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That should help me a lot with my fruits. I'm gonna accept your answer in few minutes since you're so fast.
Thanks. I missed the "space" with the concatenation. Answer has been updated.
1

Why not simply loop through each array.

$array1 = array("Apple", "Banana","Raspberry");
$array2 = array("Green ", "Yellow ","Red ")

$array3 = arrayCombine($array1, $array2);

function arrayCombine($array1, $array2) {
  $array_out = array();

  foreach ($array1 as $key => $value)
    $array_out[] = $value . ' ' . $array2[$key];

  return $array_out;
}

1 Comment

You have some syntax errors $array3 = function array_combine($array1, $array2); should be $array3 = array_combine($array1, $array2);

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.