-3

I need only array elements which have their keys in values of second array, with the fastest script.

$array_1 = array(
    'ana' => 'are',
    'du'  => 34,
    'bopq'=> "Ana are mere mereu",
    13    => "OK"
);

$array_2 = array('du', 13);

$expected_array = array(
    'du' => 34,
    13   => "OK"
);

There is faster solution than:

$expected_array = array_intersect($array_1, array_combine($array_2, $array_2);

?

3
  • So write some code and test. After that you can provide test results. Commented Jul 19, 2019 at 11:49
  • Show us your best effort and where you're stuck, so we can help you on your way. Commented Jul 19, 2019 at 11:51
  • You will have to loop over all array keys to do this. Commented Jul 19, 2019 at 11:51

1 Answer 1

1

Array_intersect_key is what you are looking for.

$array_1 = array(
    'ana' => 'are',
    'du'  => 34,
    'bopq'=> "Ana are mere mereu",
    13    => "OK"
);

$array_2 = array('du', 13);

$result = array_intersect_key($array_1, array_flip($array_2));

https://3v4l.org/P6jkq

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

1 Comment

Is the fastest from these 3 solutions we have here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.