StevenWin
StevenWin

Reputation: 35

Matching array1 value with array2 key, output matched array2 value

Is there a way to do the following:

$array1 = array( "two" => "2", "three" => "3")

$array2 = array("two", "three", "four")

I want to match array2's value with array1's key. Upon matching, I want to output array1's value.

Thank you

Upvotes: 0

Views: 100

Answers (2)

Benz
Benz

Reputation: 2335

Like Mark Baker commented, you can use array_flip() together with array_intersect_key()

$array1 = array( "two" => "2", "three" => "3");

$array2 = array("two", "three", "four");
$array2 = array_flip($array2);

print_r(array_intersect_key($array1, $array2) );

Output:

Array
(
    [two] => 2
    [three] => 3
)

Upvotes: 3

Prasannjit
Prasannjit

Reputation: 795

$array1 = array( "two" => "2", "three" => "3");
foreach($array1 as $key=>$val){
    $array_1[] = $key;
}
$array2 = array("two", "three", "four");


$result = array_diff($array2, $array_1);

print_r($result);

Upvotes: 1

Related Questions