Меню Закрыть

Php warning division by zero in

Pretty cool stuff for pretty cool people.

A division by zero error can occur in PHP whenever:

  • The variable you’re dividing with has been set to zero (this number is called the divisor).
  • The variable you’re dividing with has been set to null.
  • The variable does not exist. i.e. It has not been set.

Example code that will reproduce the error:

If you run the code above, you’ll be faced with the following error: Warning: Division by zero. This is because our variable $var has been set to 0.

Fortunately, this common warning can be avoided by carrying out some very basic checking. To avoid this type of error, you can wrap your division arithmetic inside an IF statement, like so:

какая конструкция поможет обойти деление на 0?
т.е. как сделать проверку на число, ну в конце концов запретить делить на 0

замазал конечно ошибку с помощью error_reporting( E_ERROR )

но нужно чтоб ошибки не было, вырезка из кода:

else if($func == div) <
$num3 = $num1 / $num2;
echo "$num1 / $num2 = $num3";

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.

8 Answers 8

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:

Читайте также:  Гранд мастер gm q7 multi elite отзывы

$itemCost and $itemQty are returning null or zero, check them what they come with to code from user input

also to check if it’s not empty data add:

and you can check this link for POST validation before using it in variable

If a variable is not set then it is NULL and if you try to divide something by null you will get a divides by zero error

If it shows an error on the first run only, it’s probably because you haven’t sent any POST data. You should check for POST variables before working with them. Undefined, null, empty array, empty string, etc. are all considered false; and when PHP auto-casts that false boolean value to an integer or a float, it becomes zero. That’s what happens with your variables, they are not set on the first run, and thus are treated as zeroes.

Bottom line: check if your inputs exist and if they are valid before doing anything with them, also enable error reporting when you’re doing local work as it will save you a lot of time. You can enable all errors to be reported like this: error_reporting(E_ALL);

To fix your specific problem: don’t do any calculations if there’s no input from your form; just show the form instead.

Рекомендуем к прочтению

Добавить комментарий

Ваш адрес email не будет опубликован.