Displaying Some Comma-Separated Sub-String Values from A Single String to The Checked CheckBoxes Control in PHP

Yesterday I faced a situation while I was trying to get some sub-string values that derived from a single string that being saved in database, and displayed them to the checked CheckBoxes control in PHP. Let’s say I had 5 CheckBoxes control named Applications on my form, whereas the values stored in a single string from database, for instance, is: “Application 1, Application 3, Application 5″. Then I wanted that the first, the third, and the fifth CheckBoxes would be checked based on that string. So, finally, I wrote this following code to solve my problem.

Here is the code:

<?php 
    // assuming the value of $strApplications received from database
    $strApplications = "Application 1, Application 3, Application 5";
?>
    <tr>
      <td>Applications: </td>
      <td>
        <?php  
	  for ($j=1; $j<=5; $j++) {	          
            echo '<input type="checkbox" name="applications[]" value="Application '.$j.'" ';		
	    if ( strpos($strApplications, 'Application '.$j) !== false) {
	      echo 'checked';  // which checkbox(es) should be checked
	    } else {
	      echo '';  // otherwise, leave it unchecked
	    }	
	    echo '>Application '.$j.'<br />';
          }
          ?>      
      </td>
    </tr>
Share

571 viewsPrint This Post Print This Post

Comments

  1. jr synaptics says:

    terima kasih bos, atas info dari blog ini…padahal udah mentok eh..ternyata ada jawabannya disini…tks sekali lagi..sukses slalu

Speak Your Mind

*


*