Jump to: navigation, search

Php radio

From w3cyberlearnings

Contents

PHP function myradio

This function makes HTML Radio button from array.

Syntax myradio

  • array: array input for radio button
  • checked (optional): checked value
  • name: radio name
  • return:
    • return=0, it is echo to output (default)
    • return=1, it is return
  • option:
    • option=1, it is a normal array input
    • option=2, it is an associative array input
myradio(array, $checked,name, $return=0,$option);

Function myradio()

<?php
function myradio($array, $checked, $name, $return=0, $option=1) {
	if (count($array) <= 0) {
		return;
	}
	$str_radio = "";
	if ($option == 1) {
		for ($i = 0; $i < count($array); $i++) {
			if ($array[$i] == $checked) {
				$str_radio .=
						  "<input type=\"radio\" 
			 name=\"{$name}\" 
			 value=\"{$array[$i]}\" 
			 id=\"id{$array[$i]}\" 
			 checked=\"checked\"/>";
				$str_radio .=
						  "<label 
			 for=\"id{$array[$i]}\">$array[$i]</label>";
			} else {
				$str_radio .=
						  "<input type=\"radio\" 
			name=\"{$name}\" 
			value=\"{$array[$i]}\" 
			id=\"id{$array[$i]}\"/>";
				$str_radio .=
					"<label for=\"id{$array[$i]}\">$array[$i]</label>";
			}
		}
	}

	if ($option == 2) {
		foreach ($array as $value => $label) {
			if ($value == $checked) {
				$str_radio .=
				"<input type=\"radio\" 
				  name=\"{$name}\" 
				  value=\"{$value}\" 
				  id=\"id{$value}\" 
				  checked=\"checked\"/>";
				$str_radio .=
					"<label for=\"id{$value}\">{$label}</label>";
			} else {
				$str_radio .=
					"<input type=\"radio\" 
					name=\"{$name}\" 
					value=\"{$value}\" id=\"id{$value}\"/>";
				$str_radio .=
					"<label for=\"id{$value}\">{$label}</label>";
			}
		}
	}

	if ($return) {
		return $str_radio;
	} else {
		echo $str_radio;
	}
}

?>

Example 1

<?php
$array = array(
	 'c1' => 'BMW',
	 'c2' => 'Ford',
	 'c3' => 'Honda',
	 'c4' => 'Toyota',
	 'c5' => 'Lexus',
	 'c6' => 'KIA',
	 'c7' => 'SCION');

myradio($array, 'c1', 'allcar', 0, 2);
?>

Output: HTML Source

<input type="radio" name="allcar" value="c1" id="idc1" checked="checked"/>
<label for="idc1">BMW</label>
<input type="radio" name="allcar" value="c2" id="idc2"/>
<label for="idc2">Ford</label>
<input type="radio" name="allcar" value="c3" id="idc3"/>
<label for="idc3">Honda</label>
<input type="radio" name="allcar" value="c4" id="idc4"/>
<label for="idc4">Toyota</label>
<input type="radio" name="allcar" value="c5" id="idc5"/>
<label for="idc5">Lexus</label>
<input type="radio" name="allcar" value="c6" id="idc6"/>
<label for="idc6">KIA</label>
<input type="radio" name="allcar" value="c7" id="idc7"/>
<label for="idc7">SCION</label>

Template:Php html custom functions

Navigation
Web
SQL
MISC
References