Every time a POST value is not equal to the list of values set in an array will return: Undefined Index error, I made an if statement but is not working.
Here\'s the
I'm a bit confused by your code. It looks like your array has the same key and value, so:
$products['saucepan'] = 'saucepan'
Perhaps you are trying to do this, which will check whether the product exists in the products array:
if(isset($_POST['product']) && array_key_exists($_POST['product'], $products))
{
// do stuff
}
else
{
echo "This item is not available";
}
You can just use a ??
to set set a default value if your value is not set.
$_POST['product'] ?? "No product";
With PHP 7, the null coalescing operator can be used to deal with optional request variables. You can change your $_POST['product']
reference to $_POST['product'] ?? null
which will resolve to null (rather than throwing the warning) if 'product' is not a valid key in the post array. If you wanted to check both the $_POST and $_GET arrays for a value, you would use $_POST['product'] ?? $_GET['product'] ?? null
.