Default php function that turns negative numbers in 0

前端 未结 5 613
谎友^
谎友^ 2020-12-29 01:01

Is there such a thing?

for eg

$var = -5;
echo thefunction($var); // should be 0


$var = 5;
echo thefunction($var); // should be 5
相关标签:
5条回答
  • 2020-12-29 01:22

    Simply:

    echo $var < 0 ? 0 : $var;
    
    0 讨论(0)
  • 2020-12-29 01:25

    Not built-in but, here you have:

    function thefunction($var){
       return ($var < 0 ? 0 : $var);
    }
    

    Hope this helps

    0 讨论(0)
  • 2020-12-29 01:27

    Try max($var,0), which will have the desired effect. See the manual page for more information.

    0 讨论(0)
  • 2020-12-29 01:28
    function thefunction($number){
      if ($number < 0)
        return 0;
      return $number; 
    }
    

    that should do the trick

    0 讨论(0)
  • 2020-12-29 01:36

    In PHP, checking if a integer is negative and if it is then setting it to zero is easy, but I was looking for something shorter (and potentially faster) than:

    if ($x < 0) $x = 0;
    

    Well, this is a very quick check and reset, but there is a function max that does this too and it works with arrays too.

    $x = max(0, $x); // $x will be set to 0 if it was less than 0
    

    The max() function returns the number with the highest value of two specified numbers.

    echo max(1, 3, 5, 6, 7); // 7
    echo max(array(2, 4, 5)); // 5
    echo max(0, 'hello'); // 0
    echo max('hello', 0); // hello
    echo max(-1, 'hello'); // hello
    
    // With multiple arrays, max compares from left to right
    // so in our example: 2 == 2, but 4 < 5
    $val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
    
    // If both an array and non-array are given, the array
    // is always returned as it's seen as the largest
    $val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
    
    0 讨论(0)
提交回复
热议问题