Matthew Woodard Matthew Woodard - 1 month ago 6
PHP Question

How to merge multiple arrays outside of their loops?

I am trying to create an array from 2 other arrays. I am having a problem getting them merged outside of their loops.

Here is the code to build the 2 arrays:

$redDogs = '3';
$blueDogs = '2';

$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
$reds[] = 'red_dog_' . $i++;
}

foreach ($reds as $red) {
print '<pre>'; print_r($red); print '</pre>';
}

$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
$blues[] = 'blue_dog_' . $j++;
}

foreach ($blues as $blue) {
print '<pre>'; print_r($blue); print '</pre>';
}


How could I create an array like:

print_r($alldogs);


To produce the following output:

Array {
[0] => red_dog_1
[1] => red_dog_2
[2] => red_dog_3
[3] => blue_dog_1
[4] => blue_dog_2
}


I have tried array_merge($red, $blue) but don't seem to get any values.

Any help is greatly appreciated.

Answer
$redDogs = '3';
$blueDogs = '2';

$i = 1;
// build red dogs array
$redDogs = (int)$redDogs;
while($i <= $redDogs) {
    $reds[] = 'red_dog_' . $i++;
}

$j = 1;
// build blue dogs array
$blueDogs = (int)$blueDogs;
while($j <= $blueDogs) {
    $blues[] = 'blue_dog_' . $j++;
}

print_r(array_merge($reds, $blues));

Merge your array before looping through the array.

Your foreach statements were converting your array to strings.

Comments