Skip to content

retrieve the first non-null value from collection #53372

Answered by noefleury
foremtehan asked this question in General
Discussion options

You must be logged in to vote

One snippet which assign the value to the $firstElement variable and directly stop the iteration.

$elements = collect([null, null, 'a', 'b', 'c', 'd']);

$firstElement = null; // will be filled with the first element which is considered as true

$elements->each(function ($element) use (&$firstElement) {
    if ($element) {
        $firstElement = $element;
        return false; // force stopping iteration
    }
    return true;
});

dd($firstElement); // 'a'

But maybe it could be optimized if you explain more what you are looking for.

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by foremtehan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants