PHP, How to Catch a Division by Zero

PHP, How to catch a division by zero?

if ($baz == 0.0) {
echo 'Divisor is 0';
} else {
...
}

Rather than use eval, which is highly dangerous if you're using user-input within the evalled expression, why not use a proper parser such as evalmath on PHPClasses, and which raises a clean exception on divide by zero

How do I avoid division by zero error?

Replace :

$percentage = round( ( ( $product->get_regular_price()  - $product->get_sale_price() ) / $product->get_regular_price()  ) * 100 );

by :

$percentage = 0;
if ( $product->get_regular_price() > 0 )
$percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );

Strange answer I know, but if you don't divide by zero, there is no error.

Explain :

As @domdom point out "Don't divide by zero" which is here a good answer, and a good practice since divide by zero is not "legal" in mathematics.

PHP7: Catch Division by Zerro Error

Currently the / operator doesn't throw exceptions, if the operands are numbers. In the case when a number is being divided by zero, the operator only logs a warning. Although, it does throw an error exception, if the operands are of unsupported types.

You can convert warnings into exceptions with a custom error handler, e.g.:

class DivisionByZeroException extends ErrorException {}

set_error_handler(function ($errno, $string, $file, $line, $context) {
if ($errno === E_WARNING && $string === 'Division by zero')
throw new DivisionByZeroException($string, 0, $errno, $file, $line);
throw new ErrorException($string, 0, $errno, $file, $line);
}, E_WARNING);

try {
$a = 1 / 0;
} catch (DivisionByZeroException $e) {
printf("Caught division by zero: %s at %s line %d\n",
$e->getMessage(), $e->getFile(), $e->getLine());
} catch (Throwable $e) {
printf("%s\n", $e->getMessage());
}

Output

Caught division by zero: Division by zero at /tmp/1.php line 11

Division by zero error

You'd want to check $val2 before the division occurs:

<?php
$val1 = $totalsum;
$val2 = count($allcontent);
if($val2 != 0)
{
$res = ( $val1 / $val2) * 100;
// 1 digit after the decimal point
$res = round($res, 1); // 66.7
echo "Success: ".$res."%";
}
else
{
echo "Count of allcount was 0";
}
?>

PHP Warning: Division by zero

You need to wrap your form processing code in a conditional so it doesn't run when you first open the page. Something like so:

if($_POST['num1'] > 0 && $_POST['num2'] > 0 && $_POST['num3'] > 0 && $_POST['num4'] > 0){

$itemQty = $_POST['num1'];
$itemCost = $_POST['num2'];
$itemSale = $_POST['num3'];
$shipMat = $_POST['num4'];

$diffPrice = $itemSale - $itemCost;
$actual = ($diffPrice - $shipMat) * $itemQty;
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty ;
}

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

Division by zero error?

Division by zero in PHP returns false and displays a warning message. You can squelch the warning message by appending @ to the expression in question.

$foo = @(10 / 0);

if ($foo === false) {
// Division by zero
}

It would be cleaner to just try to avoid dividing by zero in the first place though.

Suppressing warning messages is usually a sign that you should be doing something differently. For instance, simply check if the integer is 0 before using it for division.



Related Topics



Leave a reply



Submit