PHP: Avoid undefined index?

前端 未结 9 1887
闹比i
闹比i 2021-01-17 11:18

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

相关标签:
9条回答
  • 2021-01-17 11:33
    @$_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)

    0 讨论(0)
  • 2021-01-17 11:35

    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.

    0 讨论(0)
  • 2021-01-17 11:37
    if (isset($products[$_POST['product']]) && $products[$_POST['product']] == $_POST['product']) 
    

    the isset() function will help you avoid the warning

    0 讨论(0)
  • 2021-01-17 11:46
    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.

    0 讨论(0)
  • 2021-01-17 11:51

    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";
    }
    
    0 讨论(0)
  • 2021-01-17 11:55

    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..

    0 讨论(0)
提交回复
热议问题