Echo checked if checkbox is checked

12,125

Solution 1

$checked = in_array('Steak',$_POST['Filter']) ? ' checked="checked"' : '';
echo '<input type="checkbox" name="Filter[]" value="Steak" id="Filter"'.$checked.'/>';

Solution 2

What you need is in_array(), this will check whether that value exists in the array, if your array contains the value, the function will return true and you can simply echo out the checked attribute

if (in_array('YOUR_VALUE_HERE', $arr)) {
   echo 'checked="checked"';
}

You can also make a function passing value and array as parameter and returning the value from the function.

Share:
12,125
user2635574
Author by

user2635574

Updated on June 04, 2022

Comments

  • user2635574
    user2635574 almost 2 years

    if this is my checkbox

    <input type="checkbox" name="Filter[]" value="Steak" id="Filter"/>
    

    and if checkbox is checked var_export returns me

    ["Filter"]=> array(1) { [0]=> string(7) "Steak" 
    

    how do I echo "checked=checked" if checkbox is checked?

  • user2635574
    user2635574 over 10 years
    function.in-array]: Wrong datatype for second argument. what i did wrong?
  • Mr. Alien
    Mr. Alien over 10 years
    @user2635574 you are not passing array at $arr parameter, you need to use your actual array at the place of $arr
  • kejo
    kejo over 3 years
    @Mr.Alien, this answer works great if the checkbox is actually checked. If the checkbox is not checked an error occurs "Warning: in_array() expects parameter 2 to be array, null". Do you know how to correct this error if the checkboxes are left empty? Thanks.