0

I have two arrays, the following:

$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);

My second array is the following:

$arr2 = array("Key2", "Key3");

What I would like to get is the values where Key2 and Key3 matches. I would also like those values to be returned as an array so I end up with the following:

array(2,3)

Thanks for any help.

2

2 Answers 2

4

Just use of 3 three array functions to achieve this.

$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");

$arr3 = array_values(array_intersect_key($arr1, array_flip($arr2)));
print_r($arr3);

The output:

Array ( [0] => 2 [1] => 3 )

Sign up to request clarification or add additional context in comments.

Comments

1
$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");

$result = array();

foreach($arr1 as $key => $value) {
    if(in_array($key, $arr2)) {
        array_push($result, $arr1[$key]);
    }
}

var_dump($result);

or as mentioned in the comments:

$arr1 = array("Key1"=>1, "Key2"=>2, "Key3"=>3);
$arr2 = array("Key2", "Key3");

$result = array_intersect_key($arr1, array_flip($arr2));

var_dump($result);

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.