flaggalagga
flaggalagga

Reputation: 493

Select array values based on another array

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?

Upvotes: 1

Views: 488

Answers (2)

Nigel Ren
Nigel Ren

Reputation: 57131

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.

Upvotes: 0

Gufran Hasan
Gufran Hasan

Reputation: 9373

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)));

Upvotes: 3

Related Questions