How do I check if a text variable is null, false, or less than 0?

787 Views Asked by At

I am kind of new to PHP but I was having an issue. I have a PHP form that I submit. The assignment instructs that I must use a filter_input to check if the values are null. However, when i use the if/else statements it keeps stopping on the 2nd NULL option even if I input words. I check using var_dump and the variable is false. Why is the False message not coming up?

$product_name = filter_input(INPUT_POST, 'product_name');
$quantity = filter_input(INPUT_POST, 'quantity',FILTER_VALIDATE_INT);
$unit_price = filter_input(INPUT_POST, 'unit_price',FILTER_VALIDATE_INT);
var_dump($quantity);

//validate product_name
if ( $product_name == NULL) {
    $error_message = 'Please enter a valid product name'; 
//validate quantity
} else if ( $quantity == NULL)  {
    $error_message = 'Quantity is null'; 
} else if ( $quantity == FALSE ) {
    $error_message = 'Quantity must be a valid number.'; 
} else if ( $quantity <= 0 ) {
    $error_message = 'Quantity must be greater than zero.'; 
//unit_price
} else if ( $unit_price == NULL ) {
    $error_message = 'Unit Price is null';
} else if ( $unit_price <= 0 ) {
    $error_message = 'Unit Price must be greater than zero.';
// set error message to empty string if no invalid entries
} else {
    $error_message = ''; 
}

// if an error message exists, go to the purchase2.php page
if ($error_message != '') {
    include('purchase2.php');
    exit(); 
}

I expected that the FALSE message would come up but it keeps stopping at NULL and saying Quantity is null.

1

There are 1 best solutions below

3
Don't Panic On

By default, filter_input will return null if the key is not set or false if the filter fails. Unless someone has manipulated the form code before submitting it or you forgot/misnamed one of the inputs, those keys will always be present, so none of the filters should ever return null.

But since null is a falsey value, you can evaluate both possibilities the same way and it doesn't really matter which one it was.

If that key is missing from $_POST for some reason and filter_input returns null, then they didn't enter a valid value, and if it's not missing from $_POST but it's invalid and filter_input returns false, then they didn't enter a valid value. Either way they should get the same message.

if (!$product_name) {
    $error_message = 'Please enter a valid product name';
} else if ($quantity === null || $quantity === false) {
    $error_message = 'Quantity must be a valid number.';
} else if ($quantity <= 0 ) {
    $error_message = 'Quantity must be greater than zero.';
} else if ($unit_price === null || $unit_price === false) {
    $error_message = 'Unit Price must be a valid number';
} else if ($unit_price <= 0 ) {
    $error_message = 'Unit Price must be greater than zero.';
} else {
    $error_message = '';
}