Wandy Purnomo Wandy Purnomo - 7 months ago 13
HTML Question

Set checked checkbox from array

I have 2 set of array which represent all data and selected data

$all_data = ["admin","member","editor"];
$selected = ["admin","member"];


I want to make all list of data that have checked if $all_data value = $selected value
What the best method to make it possible?

Answer

Try this code -

<?php
$all_data = ["admin","member","editor"];
$selected = ["admin","member"];

foreach($all_data as $value) {
  $checked = in_array($value, $selected) ? 'checked="checked"' : '';
  echo '<input type="checkbox" name="chk[]" value="' . $value .'" ' . $checked . '>';
}
?>