You have the following in your code:
$val2 = count($allcontent);
If the $allcontent
array is empty, then the value of $val2
will be 0
, and you will essentially be doing:
$res = ( $val1 / 0) * 100;
As expected, this will cause PHP to return the 'Division by zero' error.
To make sure this doesn't happen, simply use an if
statement:
if ($val2 != 0) {
$res = ( $val1 / $val2) * 100;
// 1 digit after the decimal point
$res = round($res, 1); // 66.7
echo "Success: ";
echo $res;
echo "%";
}
This can be rewritten using sprintf()
:
if ($val2 > 0) {
$res = round( ($val1 / $val2) * 100 , 1); // 66.7
echo sprintf('Success: %d%%', $res); // % is used for escaping the %
}
It does the same thing, but looks a bit more cleaner, in my opinion.