PHP: Avoid undefined index?

@$_POST['product']

(with an @) will return the same thing as :

$product = (isset($_POST['product'])) ? $_POST['product'] : null;

Shorter is sweeter !! 4 times less code ! Easier to read and understand.

The @ symbol is the error control operator (AKA the "silence" or "shut-up" operator). It makes PHP suppress any error messages (notice, warning, fatal, etc.).

But beware not to use @ for any other thing, as it would make your code so much harder to debug!

(this will answer your question before the edit)


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";
}

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.

Tags:

Php