PHP POST array with empty and isset

后端 未结 3 1222
灰色年华
灰色年华 2021-01-15 11:26

I have the following multiple checkbox selection:

Apple


        
相关标签:
3条回答
  • 2021-01-15 11:33

    Answer:

    1. $_POST array does not contain $_POST['fruit_list']
    2. First answer is "No".A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.see in php.net
    3. Empty checks if the variable is set and if it is it checks it for null, "", 0, etc. Isset just checks if is it set, it could be anything not null. see

    0 讨论(0)
  • 2021-01-15 11:41

    use print_r() to print the post data..

    <?php 
    echo "<pre>"; print_r($_POST);
    if (empty($_POST['fruit_list']) ){
        echo "You must select at least one fruit.<br>"; 
    }
    else{
        foreach ( $_POST['fruit_list'] as $frname ){
            echo "Favourite fruit: $frname<br>";
        }
    }
    ?>
    

    If you do not select any checkbox then you will not get $_POST['fruit_list'], array index fruit_list does not exist in array

    for difference between isset() and empty() Visit Here

    0 讨论(0)
  • 2021-01-15 11:49
    1. If I don't select any of checkboxes and then submit form, does $_POST array contain an index called $_POST['fruit_list']

    No, key fruit_list does not exist

    To check if key exists in array better use array_key_exists because if you have NULL values isset returns false

    But in your case isset is a good way

    isset - Determine if a variable is set and is not NULL (have any value).

    empty - Determine whether a variable is empty (0, null, '', false, array()) but you can't understand if variable or key exists or not

    For example:

    $_POST['test'] = 0;
    print 'isset check: ';
    var_dump(isset($_POST['test']));
    print 'empty check: ';
    var_dump(empty($_POST['test']));
    
    $_POST['test'] = null;
    
    print 'isset NULL check: ';
    var_dump(isset($_POST['test']));
    
    print 'key exists NULL check: ';
    var_dump(array_key_exists('test', $_POST));
    
    isset check: bool(true)
    empty check: bool(true)
    isset NULL check: bool(false)
    key exists NULL check: bool(true)
    
    0 讨论(0)
提交回复
热议问题