1

I have 2 arrays : “Array-List” and “Array-Criteria” :

Array-List
(
    [1] => APPLE
    [2] => BANANA
    [3] => ORANGE
    [4] => LEMON
)

Array-Criteria
(
    [0] => 1
    [1] => 3
)

Is there a quick way (my Array-List can consist of thousands of entries) to select the values from Array-List based on Array-Criteria without looping through Array-List in PHP?

5
  • What is the expected result? Have you had a look at array_filter? Commented Oct 10, 2018 at 15:01
  • 2
    $arrayList[$arrayCriteria[1]] => "Orange" - Is that what you mean? If not: How is criteria else connected to the list? Commented Oct 10, 2018 at 15:01
  • What is $arrayCriteria? Commented Oct 10, 2018 at 15:02
  • what are you actually looking for? Select what values? How do the arrays link up? Commented Oct 10, 2018 at 15:02
  • If it would be SQL, it would be SELECT value FROM Array-List WHERE key IN (SELECT value FROM Array-Criteria) Commented Oct 10, 2018 at 15:05

2 Answers 2

3

Use array_intersect_key and array_flip functions to get data as:

$arr1 = Array-List
(
    [1] => APPLE
    [2] => BANANA
    [3] => ORANGE
    [4] => LEMON
)

$arr2 = Array-Criteria
(
    [0] => 1
    [1] => 3
)



var_dump(array_intersect_key($arr1, array_flip($arr2)));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so very much. This was exactly what I was looking for !
0

If you loop over the criteria, you can build a list of the macthing items...

$selected = [];
foreach ( $arrayCriteria as $element ) {
    $selected[] = $arrayList[$element];
}

Then $selected will be a list of the items your after.

Also in a quick test, it's about twice as fast as using the array_ methods.

4 Comments

True, but it's still a loop involved. I think Gufran Hasan's solution is slicker.
Not disagreeing with the other answer being good, but any solution will involve a loop.
I did some speed tests and array_intersect_key solution seems to be the fastest.
Difficult to know as it's all affected by the number of entries etc. But as I said, I tried it and found this to take 1/2 the time in my tests.

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.