Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

secondman's avatar

Collection Filter By Array

I have an array of Greenscreen List Translator scores from worst to best like so:

$hazards = [
    'BM-1'   => 8,
    'LT-1'   => 7,
    'LT-P1'  => 6,
    'LT-UNK' => 5,
    'BM-2'   => 4,
    'BM-3'   => 3,
    'BM-4'   => 2,
    'BM-U'   => 1,
    'NoGS'   => 0,
    'Not Screened' => 0,
];

I have a collection of models and I need to filter the collection down to the model with the highest score.

I have this and it does return a model, but it's not consistently the correct one.

$worst = $items->filter(function($item) use($hazards) {
    return $hazards[$item->field];
})->max();

Maybe I'm reaching for the wrong collection method?

Thanks

0 likes
7 replies
jlrdw's avatar

Look at various collection methods, you need max value, so use methods together.

You could always sort desc and top value would be answer.

secondman's avatar

@jlrdw

I already looked through all the methods.

I'm calling max on the returned collection.

jlrdw's avatar

Try

$worst = $hazards->max();
secondman's avatar

@jlrdw

First of all, hazards isn't a collection so that that would fail.

Second, how does that return the $item model with the highest score?

Even if I did

$worst = collect($hazards)->max();

That would be of zero help finding the model with the highest score.

???

secondman's avatar
secondman
OP
Best Answer
Level 17

Ok so here's a version with the map method.

$score = $items->map(function($item) use($hazards) {
    return $hazards[$item->field];
})->max();

$ha = array_flip($hazards);

$worst = $ha[$score];

Not exactly elegant but it always returns the correct item from the collection.

Thanks @jlrdw for trying to help out, much appreciated.

jlrdw's avatar

Glad you got it, you could just use the array:

        $max_key = array_search(max($hazards), $hazards);
        echo "worst is=====  " . $max_key . " | " . $hazards[$max_key];

Sorry I missed $hazards wasn't a collection.

secondman's avatar

@jlrdw

Yeah you still aren't addressing the models at all. I don't need the max value in the array, I need the item from the collection that has the highest value in the array.

Goodness.

Please or to participate in this conversation.