• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8428
  • 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
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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