PHP:How to keep checkbox value from Form data

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

This is a note of how to get the value of a checkbox from PHP form , get the check state, and check the check box at new page.
By the way, as in the code below, the use of the magic number like "$i<23" is very hard for maintenance, so try to make your own effort.

Sample code to display the check state of an input element

The value of the check box value of input elemet displayed checked by PHP code.
The "checked" parts of the code below may not be reflected if it is not written checked="checked".

<?php
/*** Displayed like <input type="checkbox" name="genre[22]" value="" checked / > ***/	
for($i=0;$i<23;$i++){
	echo  '<input type="checkbox" name="genre['.$i.']" value="" '.$check[$i].' />';
}
?>

Sample code to get the value of a checkbox for an input element

A sample code for holding the check box state(echo checked), by get the check box value of an input element.

<?php
// Get the check box value
$data = $_POST["genre"];

//Conditional branch whether to echo "checked"
for($i=0;$i<23;$i++){
	if($data[$i] != null){
		$check[$i] = "checked";
	}
}
?>
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.