Laravel 中 foreach 和 forelse 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47979448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:10:00  来源:igfitidea点击:

Difference between foreach and forelse in Laravel

laravelloopslaravel-5

提问by Gaurav Gupta

What's the basic difference between Laravel's foreachand forelse? How does forelsework?

Laravelforeach和Laravel 之间的基本区别是forelse什么?如何forelse工作?

I know that foreachduplicates your given array and works on it while in forelseit checks whether it exists and loops on it if it exists but if not it uses your provided else condition.

我知道foreach复制你给定的数组并在它上面工作,同时forelse检查它是否存在并在它存在时循环它,但如果它不存在,它使用你提供的 else 条件。

回答by RoboBear

I believe the answer to your question is that, essentially, ForElse isa ForEach loop, but with extra handling for empty input(s).

我相信你的问题的答案是,本质上,ForElse一个 ForEach 循环,但对空输入有额外的处理。

From the Laravel 5 docs on Blade Templates, an example illustrating both loops with the same list of Users as Input:

来自 Laravel 5 文档关于 Blade 模板,一个示例说明了使用相同用户列表作为输入的两个循环:

@foreach ($users as $user)
    <p>This is user {{ $user->id }}</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse


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):

现在,如果我们将其与 Laravel 框架的源代码进行比较,以查看循环是如何编译的(所有 Blades 构造在由 PHP 在网页上呈现时都被编译为 HTML):

   /**
     * Compile the for-each statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileForeach($expression)
    {
        preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches);

        $iteratee = trim($matches[1]);

        $iteration = trim($matches[2]);

        $initLoop = "$__currentLoopData = {$iteratee}; $__env->addLoop($__currentLoopData);";

        $iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';

        return "<?php {$initLoop} foreach($__currentLoopData as {$iteration}): {$iterateLoop} ?>";
    }


   /**
     * Compile the for-else statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileForelse($expression)
    {
        $empty = '$__empty_'.++$this->forElseCounter;

        preg_match('/\( *(.*) +as *(.*)\)$/is', $expression, $matches);

        $iteratee = trim($matches[1]);

        $iteration = trim($matches[2]);

        $initLoop = "$__currentLoopData = {$iteratee}; $__env->addLoop($__currentLoopData);";

        $iterateLoop = '$__env->incrementLoopIndices(); $loop = $__env->getLastLoop();';

        return "<?php {$empty} = true; {$initLoop} foreach($__currentLoopData as {$iteration}): {$iterateLoop} {$empty} = false; ?>";
    }


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.

本质上,ForElse 循环有一个内置代码并编译检查空输入,在这种情况下,它可以选择为空输入输出一个备用显示模板。

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.

我想你可以在任何可能使用 ForElse 循环的情况下使用 ForEach 循环,并补充说你包含和清空 ForElse 可能会为你捕获的检查。



Links for reference:

参考链接:

  1. Blade Templates
  2. Blade View Compile Functions
  1. 刀片模板
  2. Blade 视图编译函数

回答by milo526

The foreachloop as you described loops over each element in an array, the foreseeloop in essence is exactly the same with one extra element as you already noticed, the elsestatement. The primary use for this to use when you have an empty array.

foreach像你描述遍历在每个元素循环array中,foresee在本质上环是正好与一个额外的元素一样,你已经注意到,该else声明。当您有一个空的array.

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.

因此循环遍历所有元素,例如渲染表格的一行,但在您没有任何数据时放置一个空通知。

回答by Akshay Bhardwaj

See the basic difference is in case of no data found foreachloop you have to check countcondition and then print as per output. This will increase little bit of effort but in forelseit auto check and using @emptyyou have to echono data found..

请参阅基本区别,如果没有找到数据 foreach循环,您必须检查count条件,然后根据输出进行打印。这将增加一点点努力,但在forelse它自动检查和使用@empty你必须echo没有发现任何数据..