There are n checkboxes, with a click on each one there is an entry in the database with the user id and checkbox id in a separate table. How to check the conditions for a clicked or not clicked checkbox, so that after reloading the page the checkboxes that were checked remain marked? I tried something like this, I understand that there is an error in the cycle itself, but I don’t know how to fix it, alas:

 for ($i = 0; $i < count(массив с чСкбоксами); $i++){ if (count(массив с чСкбоксами) >0 ){ $active = ""; if (Π°ΠΉΠ΄ΠΈ чСкбокса[$i] != ""){ $active = "active" // класс для Π²ΠΊΠ»ΡŽΡ‡Π΅Π½Π½ΠΎΠ³ΠΎ чСкбокса } } $checkbox .= "<div class="check_ '.$m_active.'"></div>"; } 

It is quite clear that if, let's say, there are 3 buttons, and to release the second button, then through such a cycle the 1st and 2nd buttons will be active.

  • why this checkbox if (count (array with checkboxes)> 0) { - Naumov
  • to check if checkboxes are there at all - ddeadlink
  • You will not get inside the cycle if checkboxes are not available. so checking inside the count is really not necessary. And it is not clear why you have some kind of variable that is not tied to any specific checkboxes, it becomes active. She will become active as soon as any checkbox is found. - Mike
  • corrected, in the 3rd line the empty line accepts - ddeadlink
  • in general, I kind of expected that in the cycle itself there will be the formation of these same checkboxes. For this code, it’s not at all clear how and when this variable enters the checkbox - Mike

1 answer 1

 $ressult = array() foreach (массив с чСкбоксами as $key => $val){ $ressult[$key]['value'] = $val; if(isset($idCheckbox[$key]) != '') { $ressult[$key]['checked'] = 'checked'; } else { $ressult[$key]['checked'] = ''; } } 

get the result in the form of an array that can be iterated in the template

 <form> <?php foreach($ressult as $key => $_res): ?> <checkbox name="testing[<?php echo $key ?>]" value="<?php echo $_res['value']?>" <?php echo $_res['checked'] ?> /> <?php echo $_res['value'] ?> <?php endforeach; ?> </form> 
  • not quite clear why 2 cycles and why foreach - ddeadlink
  • in the second cycle I just showed how it can be implemented in the template if there are templates - Naumov
  • I tried to do as you suggested, it turns out as in version 1 - noted 1 and 3, rebooted, active 1 and 2 - ddeadlink
  • because if you delete the same 2 item, $ressult will look like {1,3,null} instead of {1,null,3} - ddeadlink
  • slightly corrected the name of the key in the name array that will be unique, then we can trace where and when the error occurred - Naumov