What's the basic difference between Laravel's foreach
and forelse
? How does forelse
work?
I know that foreach
duplicates your given array and works on it while in forelse
it checks whether it exists and loops on it if it exists but if not it uses your provided else condition.
I believe the answer to your question is that, essentially, ForElse is a ForEach loop, but with extra handling for empty input(s).
From the Laravel 5 docs on Blade Templates, an example illustrating both loops with the same list of Users as Input:
Now if we compare this to the source code for the Laravel Framework to see how the loops are compiled (all Blades constructs are compiled into HTML when being rendered by PHP on the web page):
Essentially, the ForElse loop has a built-in code and compile check for an empty input, in which case it optionally outputs an alternate display template for the empty input.
I would imagine you can use a ForEach loop in every case that you might use a ForElse loop, adding that you include and empty checks that ForElse might catch for you.
Links for reference:
The
foreach
loop as you described loops over each element in anarray
, theforesee
loop in essence is exactly the same with one extra element as you already noticed, theelse
statement. The primary use for this to use when you have an emptyarray
.Thus looping over all elements and for example rendering a row of a table but putting an empty notice when you do not have any data.