PHP: Elegant way to avoid division by zero

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


This is the way I would do it.

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

Tags:

Php