user2635574
user2635574

Reputation: 305

Echo checked if checkbox is checked

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?

Upvotes: 2

Views: 13526

Answers (4)

Karthik
Karthik

Reputation: 115

I think this might solve your problem

$checked = in_array('Steak',$_POST['Filter']) ? ' checked="checked"' : ''; echo '';

Upvotes: 0

user4398229
user4398229

Reputation:

<?php // Check if the box was sent.
  $checked = "";
  $status = (isset($_REQUEST['status']));
if ($status == 'checked' )  
{
  $status = 1;
  $checked = 'checked="checked"';
}
else
{
  $status = 0;
}
  echo $status; 
  echo <<<END
 <form action="" method="post">
<input type="checkbox" name="status" $checked /> Testbox<br />
<input type="submit" onclick="return showDiv();"/>
</form>
END;
?>

Upvotes: 0

MDEV
MDEV

Reputation: 10838

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

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157344

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.

Upvotes: 3

Related Questions