0

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.

1

3 Answers 3

3
$colornumber = array();
foreach ($numbers as $number){
     foreach($colors as $color){
         $colornumber[] = $number.$color;
     }
}
Sign up to request clarification or add additional context in comments.

Comments

2
<?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;

Comments

0
$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 )

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.