How to read if a checkbox is checked in PHP?

后端 未结 18 954
刺人心
刺人心 2020-11-22 07:54

How to read if a checkbox is checked in PHP?

相关标签:
18条回答
  • 2020-11-22 08:27

    Zend Framework use a nice hack on checkboxes, which you can also do yourself:

    Every checkbox generated is associated with a hidden field of the same name, placed just before the checkbox, and with a value of "0". Then if your checkbox as the value "1", you'll always get the '0' or '1' value in the resulting GET or POST

    <input type="hidden" name="foo" value="0" />
    <input type="checkbox" name="foo" value="1"> 
    
    0 讨论(0)
  • 2020-11-22 08:28

    To check if a checkbox is checked use empty()

    When the form is submitted, the checkbox will ALWAYS be set, because ALL POST variables will be sent with the form.

    Check if checkbox is checked with empty as followed:

    //Check if checkbox is checked    
    if(!empty($_POST['checkbox'])){
     #Checkbox selected code
    } else {
     #Checkbox not selected code
    }
    
    0 讨论(0)
  • 2020-11-22 08:28

    Wordpress have the checked() function. Reference: https://developer.wordpress.org/reference/functions/checked/

    checked( mixed $checked, mixed $current = true, bool $echo = true )
    

    Description Compares the first two arguments and if identical marks as checked

    Parameters $checked (mixed) (Required) One of the values to compare

    $current (mixed) (Optional) (true) The other value to compare if not just true Default value: true

    $echo (bool) (Optional) Whether to echo or just return the string Default value: true

    Return #Return (string) html attribute or empty string

    0 讨论(0)
  • 2020-11-22 08:29

    Learn about isset which is a built in "function" that can be used in if statements to tell if a variable has been used or set

    Example:

        if(isset($_POST["testvariabel"]))
         {
           echo "testvariabel has been set!";
         }
    
    0 讨论(0)
  • 2020-11-22 08:34

    filter_input(INPUT_POST, 'checkbox_name', FILTER_DEFAULT, FILTER_FORCE_ARRAY)

    0 讨论(0)
  • 2020-11-22 08:35
    $check_value = isset($_POST['my_checkbox_name']) ? 1 : 0;
    
    0 讨论(0)
提交回复
热议问题