retrieve the first non-null value from collection #53372
Answered
by
noefleury
foremtehan
asked this question in
General
-
What's the equivalent of this in collection? $keys = ['a', 'b', 'c'];
foreach ($keys as $key) {
if ($value = $this->get($key)) {
break;
}
} it should not iterate over all keys |
Beta Was this translation helpful? Give feedback.
Answered by
noefleury
Nov 1, 2024
Replies: 2 comments
-
Use ->filter(fn($bar)=>$bar===null)->first(); |
Beta Was this translation helpful? Give feedback.
0 replies
-
One snippet which assign the value to the $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. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
foremtehan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One snippet which assign the value to the
$firstElement
variable and directly stop the iteration.But maybe it could be optimized if you explain more what you are looking for.