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?

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
flaggalagga
  • 451
  • 5
  • 14

2 Answers2

2

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)));
Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
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.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55