PHP: Elegant way to avoid division by zero

后端 未结 7 579
小鲜肉
小鲜肉 2020-12-30 07:19

Much like this site, my current project has reputation and in the script that I\'m working on I need to calculate the ratio between two users\' reputations.

         


        
7条回答
  •  死守一世寂寞
    2020-12-30 07:46

    Use a ternary operator to check if the divider is zero or not.

    $attacker->ratio = $attacker->rep > 0 ? $defender->rep / $attacker->rep : 1;
    $defender->ratio = $defender->rep > 0 ? $attacker->rep / $defender->rep : 1;
    

    Use whatever you wish instead of the value 1 as default.

提交回复
热议问题