if ($unitWeight != 0)
{
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
I'm expecting this statement to run only if $unitWeight is greater than 0. It seems to run no matter what and I get this error.
"Warning: Division by zero in"
Try typecasting the your variable
$unitWeight = (int) "0";
var_dump(($unitWeight));
Or use abs()
or intval()
$unitWeight = "0";
var_dump(abs($unitWeight));
Use greater than ( > )
if ($unitWeight > 0)
{
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
Use method empty() for checking code like this because empty() also check is the $unitWeight
are set somewhere
if ( !empty($unitWeight) ){
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
If you want the statement to run only if $unitWeight
is > 0, then that is what you should use.
See below:
if (intval($unitWeight) > 0){
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
Use intval() to get intval — Get the integer value of a variable
as described in the official documentation here
Please keep in mind, it is always beneficial and imperative that you sanitize your input and ensure that only numeric values are accepted.
As the previous answer try using
if ($unitWeight > 0){
$saleableUnits = ($sumQty/$unitWeight);
$unitCost = ($sumCost/$saleableUnits);
}
And the big thing is may be already the $unitWeight
must be greater than 0
i think, that's why it is always going inside the if condition.
before the if condition try printing the value of $unitWeight
variable, so that you can find what is inside the variable and also the reason why it gets inside the condition.
Then finally like same print the variables $sumQty
and $sumCost
.
might be any of these variable have a value of 0
that is why it is showing the error you have mentioned
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.