• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8050
  • Last Modified:

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?
0
bergstrom_davin
Asked:
bergstrom_davin
  • 3
  • 2
  • 2
  • +1
1 Solution
 
MasonWolfCommented:
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.
0
 
bergstrom_davinAuthor Commented:
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.
0
 
MasonWolfCommented:
($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)
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Cornelia YoderArtistCommented:
bah, the easy way:

$number = max(0, $number);
0
 
MasonWolfCommented:
"You da man" yoder

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

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now