Takeov3r
Takeov3r

Reputation: 25

Combine 2 arrays only if their key index match

I want to combine this arrays:

$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);

I want this:

$arr3 = array("a" => 5, "c" => 7, d => 9);

I want to ignore the key index "2" on $arr1 because it doesnt exists on $arr2.

So, I want to combine only if the key index match, combining only values with same original keys.

Upvotes: 0

Views: 131

Answers (6)

Christian
Christian

Reputation: 1577

Try this:

$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
$result = array_combine(array_intersect_key($arr1, $arr2), $arr2);

Which produces:

Array
(
    [a] => 5
    [c] => 7
    [d] => 9
)

Upvotes: 1

Miton Leon
Miton Leon

Reputation: 284

Simple way use array_key_exists:

$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");

$arr2 = array(1 => 5, 3 => 7, 4 => 9);

$new = array();
foreach ($arr2 as $key => $value) {
     if(array_key_exists($key, $arr1)) {
         $array[$arr1[$key]] = $arr2[$key];
     }
}

 print_r($array);

Array ( [a] => 5 [c] => 7 [d] => 9 )

Upvotes: 0

Deenadhayalan Manoharan
Deenadhayalan Manoharan

Reputation: 5444

Try this..

Use "array_key_exists"

 $arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);

foreach($arr1 as $key=>$value)
{
if (array_key_exists($key, $arr2)) {
$arr3[$value]=$arr2[$key];
}
}

print_r($arr3);

Array ( [a] => 5 [c] => 7 [d] => 9 )

Upvotes: 0

Denis Makula
Denis Makula

Reputation: 48

You can try something like this:

function combineArrays( $array1, $array2 ){
    $array3 = array();
    foreach ($array1 as $key => $value) {

        if( isset($array2[$key]) ) { $array3[$value] = $array2[$key]; }

    }

    return $array3;
}

use it like:

$arr3 = combineArrays($arr1, $arr2);

Upvotes: 0

Exploit
Exploit

Reputation: 6386

you would do something like this, its not tested but i'd assume it'll work. What @Adrian said looks better. I didnt use foreach($array as $key=>$val). that is better.

//first merge all arrays into one (if you want)
$data = array_merge($arr1, $arr2);
$bucket = array();
$ignored = array('2', '3', '4') //array indexes to ignore

foreach($data as $item)
{
    if(in_array($item[$ignored]))
    {
        continue;
    }
    else
    {
        array_merge($bucket, $item);
    }
}

Upvotes: 0

Adrian
Adrian

Reputation: 70

Here you go.

<?php
$arr1 = array(1 => "a", 2 => "b", 3 => "c", 4 => "d");
$arr2 = array(1 => 5, 3 => 7, 4 => 9);
$arr3 = array();
foreach ($arr1 as $key => $value) {
    if(isset($arr2[$key])){
        $arr3[$value] = $arr2[$key];
    }
}

print_r($arr3);
?>

Upvotes: 1

Related Questions