Wistar
Wistar

Reputation: 3790

PHP merge values of numeric arrays in corresponding keys

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

Upvotes: 2

Views: 176

Answers (2)

PassKit
PassKit

Reputation: 12591

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;
}

Upvotes: 1

hafichuk
hafichuk

Reputation: 10781

You actually should loop through arrays to combine them.

$combinedArray = array();
foreach ( $array1 as $key=>$value ) {
    $combinedArray[$key] = $array2[$key] . ' ' . $array1[$key];
}

Upvotes: 2

Related Questions