避免除以零错误 Laravel 框架

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32755983/
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 12:23:49  来源:igfitidea点击:

Avoid The Divide by Zero Error Laravel Framework

phplaravellaravel-5

提问by Phil Nind

I am trying to calculate some stats on my Laravel site...however when I execute the following code it is giving me a 'Divide By Zero Error'

我正在尝试在我的 Laravel 站点上计算一些统计数据……但是,当我执行以下代码时,它给了我一个“除以零错误”

I understand why because there are no records so the calculation is 0 divide 0

我明白为什么因为没有记录所以计算是 0 除以 0

Is there a way that if it eqauls zero to echo '0' rather than throw up that error

有没有办法,如果它等于零来回显“0”而不是抛出那个错误

Controlller

控制器

    private function getAverageOddsForLastMonth()
{
    $firstDayOfLastMonth = new Carbon('first day of last month');
    $lastDayOfLastMonth = new Carbon('last day of last month');

    $tipslastmonth = Tip::whereBetween('tip_date',
        [
            $firstDayOfLastMonth,
            $lastDayOfLastMonth
        ]
    )->count();

    $sumOfTheOddsLastMonth = Tip::whereBetween('tip_date',
        [
            $firstDayOfLastMonth,
            $lastDayOfLastMonth
        ]
    )->sum('odds');

    return ($sumOfTheOddsLastMonth / $tipslastmonth);
}

回答by Thomas Ruiz

Just add a simple condition:

只需添加一个简单的条件:

return $tipslastmonth == 0 ? 0 : ($sumOfTheOddsLastMonth / $tipslastmonth);

回答by Vinay Kaithwas

  • As you know, This error occurs Because of 0 in your Variable Simply you do this
  • 如您所知,发生此错误的原因是变量中的 0 只需执行此操作
if($tipslastmonth != 0)     
    $tipslastmonth = $sumOfTheOddsLastMonth / $tipslastmonth;  
else     
    $tipslastmonth = 0;
  1. When 0 not occur else part will be executed work fine with my project
  1. 当 0 不发生时,其他部分将在我的项目中正常执行