Skip to content

Setting Negative Numbers to Zero in PHP

1 min read

A simple little trick in PHP for when you need to make sure that a value doesn’t drop below zero. For example, you might be subtracting a discount from a basket total and not want the amount to be paid to become negative.

You could do this using a condition like this:-

$total = -8;
echo $total > 0 ? $total : 0; // Outputs '0'

However, PHP has an method for doing this for us. We can use the max method.

$value = -9;
echo max($value, 0); // Outputs '0'

All max does is return the larger number. So if $value is negative in this example 0 will be the larger number and be returned. If $value was positive, it would be greater than 0 and therefore $value would be returned.

© 2024 Andy Carter