PHP Echo Tutorials

Common Math Problems

Written by phpecho.com   

Any application or program finally does some operations on the inputs provided. The input could be provided by the user or the application itself. More often than not, there could be mathematical operations involved in the program. Mathematical operations bring with them a unique set of problems. We look at a couple of common math ‘gotchas’ in PHP. You do not need to wait for your program to fail before you correct these. You can check for these whenever you do any mathematical operations in your programs.


Division by zero

This is one of the ‘silliest’ errors you will get while working with numbers. But this kind of error becomes silly only when you have identified the issue! As you would have studied in high school, you cannot divide a number by zero. PHP throws a warning if you try the operation. The following code is an example of this type of issue.

   <?php
   $num = 10;
   $den = 0;
   echo ("The value when dividing by zero is - ".$num/$den);
   ?>


When this piece of code is executed a warning will be thrown about dividing by zero. Note that program execution does not stop and the output is


Warning: Division by zero in maths.php on line 4

The value when dividing by zero is –

Note that even though the program has executed, there is no value for the mathematical operator. That is not surprising though!

You can eliminate this issue by ensuring that you do not divide using 0. If the denominator is itself calculated during runtime, you may be better off validating to ensure that you do not divide by zero. The example below shows the approach:

<?php
   $num = 10;
   $den = 0;
   if ($den != 0){
                   echo ("The value when  dividing by zero is - ".$num/$den);
   } else {
                   echo ("Some error  message here");
   }
   ?>


Issue of NaN

Nan stands for ‘Not a Number’. It is a peculiar value in that this is treated as a number even though you cannot do the common operations allowed with numbers. When we say not allowed, we mean that you will not get the expected outputs.

NaN will arise when the mathematical function used has gone out of range. For example, if you try to find the arccosine of 10, you will end up with NaN. When you perform any operation with NaN (for example, adding a non-NaN value with NaN), then the result is always NaN.

Another peculiar thing about this value is that it is not equal to itself. Yes, you read that right. If you compare NaN with NaN, the result will be false.
Due to their very nature, resolving issues involving NaN is complicated. They infect others and change their values also to NaN. The best way to debug such issues is by printing the output of each line to the console/browser and tracking the issue.

If you can take care of the above mentioned two issues, you can breathe easy because you will not run into mathematical problems in PHP.