PHP: Elegant way to avoid division by zero

后端 未结 7 464
小鲜肉
小鲜肉 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 08:06

    Assuming positive numbers are valid then ensure the lowest divisor value will be 1.

    $defender->ratio = $attacker->rep / max($defender->rep, 1);
    

    // --------------------------------------------

    suggested code by someone else,

    @php_nub_qq suggested alternate code...
    In today's php

    $defender->ratio = $attacker->rep / ($defender->rep ?? 1);
    

    Alas, this code provided by @php_nub_qq does not work in PHP 7.4 ;-( see @OceanBt in the comments... I thank them for the correction! :)

    so, Here I am maintaining code that I never was interested in. And now, is shown to be PHP version specific! Here is the correction...

    $y = 100/($x ?: 1);

    Why am I doing this? 1) Notice my code still works fine! Avoid 'clever features' for production code. 2) Because someone believes that have a 'better answer' doesn't mean they do!

    I don't mind doing this maintainance of the code of someone else! This is the real world! We have to do this. I posted it because:
    I really am trying to help programmers to learn.

    // My thoughts about the 'improvement' to what I posted...

    imo, that suggestion of yours isn't the same as my approach! I specifically used 'max' as it forces a limit on a range of numbers. You can nest the 'min' and 'max' functions also to force a limited range.

    Your method is a 'selection' and not why I did the answer I did. :)

提交回复
热议问题