Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a way to add elements from one array to each of the elements in another array ?

For example:

$color = array("black", "white", "yellow");

$number = array("1", "2", "3");

I want a new array to combine them all so it's :

$colornumber = array("1black", "1white", "1yellow", "2black", "2white", "2yellow" etc.)

Thanks.

share|improve this question

3 Answers

up vote 3 down vote accepted
$colornumber = array();
foreach ($numbers as $number){
     foreach($colors as $color){
         $colornumber[] = $number.$color;
     }
}
share|improve this answer
 
You were so fast.. I made solution with foreach but no reason to post it here :D –  DeiForm Jul 27 at 7:56
 
I was wrong ... just corrected it –  Orangepill Jul 27 at 7:57
 
ye this is what I had –  DeiForm Jul 27 at 7:58
<?php 
$colors = array("black", "white", "yellow");
$numbers = array("1", "2", "3");
$colors_numbers = array();

foreach ($numbers as $number):
   foreach ($colors as $color) {
    $colors_numbers[] = $number . $color;
   }
endforeach;
share|improve this answer
 
You had it right the first time. –  Orangepill Jul 27 at 7:58
 
I appreciate the gesture, @Orangepill –  Matanya Jul 27 at 8:08
$color = array("black", "white", "yellow");

$number = array("1", "2", "3");

function mergeArr($arr1,$arr2){

    if(is_array($arr1)&& is_array($arr2)){
$newArr = array();
foreach($arr1 as $val1){
    foreach($arr2 as $val2){
    $newArr[] = $val2.$val1;

    }
}
return $newArr;
}else{
return false;
}

}

print_r(mergeArr($color ,$number));

OUTPUT:

Array ( [0] => 1black [1] => 2black [2] => 3black [3] => 1white [4] => 2white [5] => 3white [6] => 1yellow [7] => 2yellow [8] => 3yellow )
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.