Home  >  Article  >  Backend Development  >  How to automatically generate a set of radio buttons with PHP

How to automatically generate a set of radio buttons with PHP

不言
不言Original
2018-08-28 17:11:213134browse

This article mainly introduces how to use PHP to automatically generate a set of radio selection codes.

The main idea is: use php to form the html code that creates the radio button, and return it to the browser, and the browser can parse the html code.

Code sample:

<?php 
	header(&#39;Content-type:text/html; charset=utf-8&#39;);
	// 编写函数实现自动生成一组单选按钮
	function radioFun($arr, $name, $checked) {
		// 定义保存html代码的变量
		$html = &#39;&#39;;
		foreach ($arr as $key => $value) {
			# 遍历数组,分别形成不同的单选框html代码
			if ($checked == $value) {
				// 若默认选中的值遍历到了,则形成下述html代码
				$html .= "<input type=\"radio\" name=\"$name\" checked=\"checked\" >$value";
			} else {
				// 若不是默认选中的值,则形成如下普通单选框html代码
				$html .= "<input type=\"radio\" name=\"$name\" >$value";
			}
		}
		// 返回完整的html代码交由浏览器解析
		return $html;
	}

	// 测试数据
	$color = array("红色", "黑色", "绿色", "蓝色");
	echo radioFun($color, "color", "绿色");
?>

Hope it will be helpful to friends in need.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn