Today I noticed a divide by zero error in the error log for my Voltage Drop Calculator. That didn't make sense to me because I test to see if a value is being divided by zero before doing a divide. That's pretty basic computer programming logic.
However the test to see if the variable was zero wasn't working. If I put a number in the Cross Section field the calculation works perfectly. When I put a zero in the Cross Section field the zero was effectively being ignored. This didn't make sense to me.
I'll admit this is a limitation of my knowledge of PHP. Each programming language has it's quirks (features) and this is one of PHP's that I missed and to be fair, it was bad programming on my part.
When receiving the variable in the URL I would then use if ( $_GET['variable']) to test to see if the variable had a value. What I didn't know was a zero value is treated as being empty. Thus when I later tested the value of the variable against zero the test was false and a divide by zero would occur because the calculation would be performed.
What I really should have done (and have now done) in the code is to test if the variable was set. I've now updated the code to be, if ( isset($_GET['variable']) ) and the code works as it should.
I'm sure if I've made this simple mistake others may also fall into this trap. Hopefully others can learn from my mistake.
Kelvin Eldridge
www.OnlineConnections.com.au
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.