How to take the value of $_GET['sealed'] to leave the checkbox selected using PHP

Asked

Viewed 183 times

0

I have an array in PHP that are the values selected from the checkbox, which were obtained by $_GET:

$_GET['selecionados'] = array(2) { 
[0]=> string(1) "a" 
[1]=> string(1) "b"  
}

There I have the chekboxes:

foreach($selecoes = $check){
echo '<input type="checkbox" value="'.$check->valor.'" name="selecionados[]" id="'.$check->valor.'">
}

he prints:

<input type="checkbox" value="a" name="selecionados[]" id="a">
<input type="checkbox" value="b" name="selecionados[]" id="b">
<input type="checkbox" value="c" name="selecionados[]" id="c">
<input type="checkbox" value="d" name="selecionados[]" id="d">

I need that if the value of selected is in $_GET['selected'], it is marked "checked". in this example would be:

<input type="checkbox" value="a" name="selecionados[]" id="a" checked>
<input type="checkbox" value="b" name="selecionados[]" id="b" checked>
<input type="checkbox" value="c" name="selecionados[]" id="c">
<input type="checkbox" value="d" name="selecionados[]" id="d">

How to do it? I imagine using str_replace, but I don’t know exactly how.

  • pq wrote wrong...rs, values are c and d, I am changing the question...

  • You have already described the logic: if you are in $_GET['selecionados'] adds checked. How you tried to implement this?

  • the ones I tried didn’t work. I tried to use echo str_replace('id="'. $_GET['selected']. '"', 'id="'. $_GET['selected']. '" checked', $option) ( the $option declared as '<input type="checkbox" value="'. $check->value. '" name="selected[]" id="'. $check->value.'">'

  • Put in question the trials and results of each

1 answer

1


You can inside the foreach that shows the checkbox, check if the value is in the $_GET['selected array], the code would look like this:

foreach($selecoes as $check){
  $checked = (in_array($check->valor, $_GET['selecionados']))?'checked':'';
  echo '<input type="checkbox" value="'.$check->valor.'" name="selecionados[]" id="'.$check->valor.'" '.$checked.'>';
}

The function in_array() checks if the value exists at the position of the array, so if it exists it marks as checked.

  • tried but gave error, in the middle of echo you are opening the "<?" I think there gave error Parse error: syntax error, Unexpected ')' in

  • Exactly, I ended up neglecting and I didn’t see that I was inside the echo, now this OK.

  • I also edited your foreach, where it was $selecoes = $check I switched the = for as, it was he who was generating his mistake.

  • perfect, this was going to speak...rs, now gave right, just to understand, the in_array see if the $check->value is within the $check->value, so if you have it print checked?

  • That, in_array() checks if the $check->valor is on the array $_GET['selecionados'], if you want you can see documentation here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.