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
@$_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)
You should first check to see if $_POST['product'] is set with isset(), like:
if( isset($_POST['product']) ){
// Do something with $_POST['product']
}
That should suppress the warning.
if (isset($products[$_POST['product']]) && $products[$_POST['product']] == $_POST['product'])
the isset() function will help you avoid the warning
if(isset($products[$_POST['product']) && $products[$_POST['product'] != "")
Note that a vriable can be empty but also "set" so the what comes after the && is necessary.
you can check whether the index 'product' is defined in the same if statement ..
if (isset($_POST['product']) && $products[$_POST['product']] == $_POST['product']) {
do everything;
}
else {
echo "This item is not available";
}
You could also try
$product = (isset($_POST['product'])) ? $_POST['product'] : null;
This will set $product to the $_POST value if it exists, or to null if not. Then you could try
if ($product) {
do_something();
}
or access your array with
$products[$product];
I feel this way it makes your code that little bit easier on the eyes..