Link to home
Start Free TrialLog in
Avatar of bergstrom_davin
bergstrom_davin

asked on

PHP: If negative then zero

Besides the obvious:
if ($x >= 0) echo $x; else echo 0;
or
echo ($x >=0 ? $x : 0);
Is there a single or built in php statement that will convert a number that is negative to 0?
Avatar of MasonWolf
MasonWolf
Flag of United States of America image

I don't think so, but even if there was, it wouldn't be any faster than

($x >= 0) ? $x : 0;

That's just about as quick as you can get right there.

Is there a particular reason that won't work? Maybe I can suggest a workaround.
Avatar of bergstrom_davin
bergstrom_davin

ASKER

That does, but the problem is length on the line of code. (designer in me)

Here is a snippet of code:
($totalchars-strlen($title) > 0 ? $totalchars-strlen($title) : 0))

Would be nicer as
phpfun ($totalchars-strlen($title) )

Its not a big deal in this case but I may end up reusing this, so before I right a function I just want to ensure php did'nt have one already.
($totalchars>strlen($title) ? $totalchars-strlen($title) : 0)
is slightly shorter than
($totalchars-strlen($title) > 0 ? $totalchars-strlen($title) : 0)

I don't think you can get any simpler than that though.

If you want even shorter, where simplicity is less of an issue, then there's this option:
(($x = $totalchars-strlen($title)) > 0 ? $x : 0)
ASKER CERTIFIED SOLUTION
Avatar of Cornelia Yoder
Cornelia Yoder
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
"You da man" yoder

Nice job.
Actually, I'm 'da woman', but thanks :)
Good one Yodercm.  i could not think out of the obvious.  :-)
Brilliant, exactly what I was looking for.