Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Warning: Division by zero

I'm learning php and built an experimental form-based calculator (also using html & POST method) that returns values to a table. The calculator is functional when I enter my values and click submit, but I keep getting two "Division by zero" errors on the last line when I first run the code. I can't seem seem to find a logical solution or explanations when searching here or via Google. Any explanation you can provide to a newb will be appreciated.

<?php 

error_reporting(E_ALL ^ E_NOTICE);

//calculate the difference in price

$itemQty = $_POST['num1'];

$itemCost = $_POST['num2'];

$itemSale = $_POST['num3'];

$shipMat = $_POST['num4'];

$diffPrice = $itemSale - $itemCost;

$actual = ($diffPrice - $shipMat) * $itemQty;

$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty ;

?>
like image 397
Chip Avatar asked Aug 23 '13 17:08

Chip


1 Answers

If the expected value can be 0 (therefore does not need validation), I do this to keep things in one line:

$percentage = $sum1 / ($sum2 ?: 1)
like image 161
digout Avatar answered Oct 11 '22 15:10

digout