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

0

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

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

Here are the chekboxes:

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

it 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 if the selected value is in $ _GET ['selected'], it is marked as checked. this example would look like this:

<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 it's using str_replace, but I do not know exactly how.

    
asked by anonymous 19.10.2018 / 14:46

1 answer

1

You can inside the foreach that shows the checkboxes, check if the value is in the $ _GET ['selected'] array, the code looks 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 in_array () function checks whether the value exists in an array position, so if it exists it checks.

    
19.10.2018 / 19:07