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

intossh@gmail.com's avatar

Collection: get multiple keys

Hello, I am wondering if there is some method to use on Collections, similar to:

$request->only(['some', 'keys', 'to', 'get']);

Sometimes I have a collection containing many keys which I don't need to get, and I would like some fast way to get the ones I need. I know I can specify them manually, but this would be faster. For now I made a helper:

function collectionGetArray(Collection $collection, $keys) {
    $output = array();
    foreach ($keys as $key) {
        $output[$key] = $collection->get($key);
    }
    return $output;
}

But I would like to know if I am missing some official way.

Thank you.

0 likes
4 replies
johnatan.cunha's avatar

You can use map callback

$collection->map(function($item){return [$item->param1,$item->param2,$item->param3];}

Please or to participate in this conversation.