Divide by 0 Error in PHP calculator
I have a simple calculator with code shown below. I have 3 inputs and a simple equation. But i keep getting a divide by 0 error even before i click the calculate button. What am I doing wrong here?
<?php if (isset($_POST['valuea'])) $valuea = $_POST['valuea']; if (isset($_POST['valueb'])) $valueb = $_POST['valueb']; if (isset($_POST['valuec'])) $valuec = $_POST['valuec']; $answer = ($valuea - $valueb) / $valuec; echo <<<_END <form method='post' action='/depreciation.php'> <table border='0' width='500px' cellpadding='3' cellspacing='1' > <tr ><td colspan="2"><strong>Stright Line Depreciation</strong></td> </tr> <tr ><td>Enter Cost:</td><td align="center"><input type='text' name='valuea' value="$valuea"/></td></tr> <tr ><td>End Salvage Value:</td><td align="center"><input type='text' name='valueb' value="$valueb"/></td></tr> <tr ><td>Enter Estimated Life:</td><td align="center"><input type='text' name='valuec' value="$valuec"/></td></tr> <tr ><td colspan="2"><input type='submit' value='Calculate'/></td></tr> _END; ?> <tr > <td><i>The answer is:</td> <td align="center"><input type="text" value="<?php echo round($answer)?>"></td></i> </tr> </table> </form>
$answeris being evaluated on page load, as dc2 commented, nothing is stopping your code from being executed as soon as you load the page...
$answer = ($valuea - $valueb) / $valuec;
this produces your error when you load the page.
To avoid this you should check for 0 before you do the division:
So it looks like you check in the first three lines of code to see if the $_POST variables are set, but then regardless of whether they are or not, you go ahead and assign $answer a value. So what happens if those values aren't set?
I haven't written PHP in some time, so I may be wrong, but you may want to check $_POST for data prior to executing any code whatsoever and if you find nothing has been set, redirect the user to the form that they should have filled out.
Just my $0.02 - let me know if it works.
You could change
Then you will avoid the calc with empty values
I'd take advantage of is_numeric and also test for 0 before dividing like so:
Here's a phpfiddle and its results.