Check if input has negative value

0

I have this example that checks if the input is only receiving numbers, in case it checks if it has only positive numbers, if I add for example a 0 it no longer works, I have to add two zeros 00 , see:

elseif (!is_numeric($adminAmount)) {
    echo json_encode(array(
        'error'     => true,
        'message'   => 'A quantidade deve ser apenas números.'
    ));
}

If it's numbers continues, otherwise it returns the error message.

Is there a native PHP function that checks whether the number is positive or negative? for example +1 or -1 ?

    
asked by anonymous 08.11.2017 / 22:39

1 answer

2

You do not need a function just for this, to check if it is positive or negative, just use < or > , for example:

$input = 1;

if ($input > -1) {
   echo 'Positivo';
} else if ($input < 0) {
   echo 'Negativo';
}

Or <= and >=

$input = 1;

if ($input >= 0) {
   echo 'Positivo';
} else if ($input <= -1) {
   echo 'Negativo';
}
Now about the behavior of 00 working and a 0 is not very strange, I assume you've messed up, anyway you can try using parseFloat , because you may not even be receiving a valid number , for example:

$adminAmount = parseFloat($adminAmount);

Yet it is best to check the format you received first

var_dump($adminAmount);

Using filter_var and filter_input

You can use filter_var to limit a range , for example only accept numbers above 0 :

$adminAmount = filter_var($adminAmount, 
                      FILTER_VALIDATE_INT, 
                      array('options' => array('min_range' => 0)));
  

You control the range in array('min_range' => 0)

If the data comes from GET or POST you can use filter_input :

$adminAmount = filter_input(INPUT_GET, 'admin-amount',
                      FILTER_VALIDATE_INT, 
                      array('options' => array('min_range' => 0)));
  

'admin-amount' is the name of <input>

If it's POST:

$adminAmount = filter_input(INPUT_POST, 'admin-amount',
                      FILTER_VALIDATE_INT, 
                      array('options' => array('min_range' => 0)));
    
08.11.2017 / 22:44