PHP: Elegant way to avoid division by zero

后端 未结 7 564
小鲜肉
小鲜肉 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:00

    Based upon the other answers I'll assume you only update the ratio if it's not zero (Remember you asked for elegance not clarity):

    if( !empty($attacker->rep) ) { 
        $attacker->ratio = $defender->rep / $attacker->rep;
    }
    

    PHP treats 0 as empty.

提交回复
热议问题