Combine each key and value of array with another array Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Combine each key and value of array with another array without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have this two arrays:

$arr1 = Array ( 600 => 580, 500 => 480, 100 => 80 ) <- always 3

$arr2 = Array ( 'filt' => grey, 'or' => 90 ) <- this array is dynamic

How can I combine each key and value from first array with the other array? I mean, I need:

$array = ( 600 => 580, 'filt' => grey, 'or' => 90 )
$array = ( 580 => 480, 'filt' => grey, 'or' => 90 )

successively in for/foreach loop. How can I do this? Thanks a lot, im new on php ^^ and sorry for my english 😛

Answer

I think you need this. Just loop through the first array, copy the first array in the out array and add key, value of loop array into the out array.

As you mention:

$array = ( 600 => 580, 'filt' => grey, 'or' => 90 )
$array = ( 580 => 480, 'filt' => grey, 'or' => 90 )

I think you need to create different array each time. For each of the element of first array you need different array as output.

$arr1 = array( "600" => 580, "500" => 480, "100" => 80 );
$arr2 = array( 'filt' => "grey", 'or' => 90 );

$out = array();
foreach($arr1 as $key => $value){
    $out = $arr2;
    $out[$key] = $value;

    print_r($out);
}

Result

First Iteration:

Array
(
    [filt] => grey
    [or] => 90
    [600] => 580
)

Second Iteration:

Array
(
    [filt] => grey
    [or] => 90
    [500] => 480
)

Third Iteration:

Array
(
    [filt] => grey
    [or] => 90
    [100] => 80
)
We are here to answer your question about Combine each key and value of array with another array - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji