-1

I have a problem to put <?php echo $myArray[0] === 'true' ? 'checked' : ''; ?> into <input type="checkbox" id="checkbox_val" name="checkbox_val" value="1" > . Because I need to define checked in the input. Hope someone can guide me on how to solve this problem.

Below is my sample code, but cannot work:

<?php

    $check_value = 'true,false,false,false,true,false,false';
    
    
    $myArray = explode(',', $check_value);

    foreach ($myArray as $k => $va) { 
    }
    
    
    foreach ($result_arr_user as $val_user) {
    $checkbox = '<input type="checkbox" id="checkbox_val" name="checkbox_val" value="1" echo $myArray[0] === 'true' ? 'checked' : ''; >&nbsp;';
    }
?>
1
  • what does $result_arr_user contain? Commented Jun 2, 2021 at 4:32

2 Answers 2

2

You can simply re-write input checkbox as

$checkbox = "<input type='checkbox' id='checkbox_val' name='checkbox_val' value='1' ".($myArray[0] === "true" ? "checked" : "")." >";

Loop

<?php

   $check_value = 'true,false,false,false,true,false,false';
   $myArray = explode(',', $check_value);   
   for ($i = 0; $i <= count($myArray); $i++) {
     $checkbox = "<input type='checkbox' id='checkbox_val' name='checkbox_val' value='1' ".($myArray[$i] === "true" ? "checked" : "")." >";
     echo $checkbox;
   } 
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your answer. If I want to use $i to replace 0, do you know how to do it? I use this method cannot word $checkbox = "<input type='checkbox' id='checkbox_val' name='checkbox_val' value='1'".($myArray[$i] === "true" ? "checked" : "")." >";
Check the updated answer for this comment answer.
0
<?php

    $check_value = 'true,false,false,false,true,false,false';
    
      $myArray = explode(',', $check_value);
     
    
    foreach ( $myArray  as $val_user) {
        if($val_user=='true')
        {
        
    $checkbox = '<input type="checkbox" id="checkbox_val" name="checkbox_val" value="1"  checked="true">';
        }   
        else
        {
             $checkbox = '<input type="checkbox" id="checkbox_val" name="checkbox_val" value="1" >';
            
        }
   }
?>

You can simply write in this way

2 Comments

input tag checked is a property not attribute. So checked="true" and checked="false" are same.
So remove checked="false" from else condition updating the code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.