Php 回显html时的If语句
所以我尝试用循环生成select值。这里的问题是我不能使用if语句。我可以将一些字符串和一些if语句组合在一起,但这似乎是一个奇怪的解决方案Php 回显html时的If语句,php,html,Php,Html,所以我尝试用循环生成select值。这里的问题是我不能使用if语句。我可以将一些字符串和一些if语句组合在一起,但这似乎是一个奇怪的解决方案 <select name="test"> <option disabled selected> -- Select an industry -- </option> <?php $numberOfIndustries = co
<select name="test">
<option disabled selected> -- Select an industry -- </option>
<?php
$numberOfIndustries = count($industryOptions); //industryOptions is an array
for($i = 0; $i <= $numberOfIndustries; $i++) {
echo "<option" . if (isset($_POST['test']) == true && $_POST['test'] == $industryOptions[$i]) { . "selected='true'" . }; . "value=" . $industryOptions[$i] . ">" . $industryOptions[$i] . "</option>";
}
?>
</select>
--选择一个行业--
您不能使用
(点)连接IF
子句-仅字符串。相反,您可以使用
因此,您的echo
调用应如下所示:
echo "<option " .
(isset($_POST['test']) && ($_POST['test'] == $industryOptions[$i]) ? "selected='true' " : "").
"value=" . $industryOptions[$i] . ">" . $industryOptions[$i] . "</option>";
echo”“$行业选项[$i]。"";
只需单独回显,而不是创建一个无法读取的庞大语句
<?php
$numberOfIndustries = count($industryOptions); //industryOptions is an array
for($i = 0; $i <= $numberOfIndustries; $i++) {
echo "<option";
if (isset($_POST['test']) == true && $_POST['test'] == $industryOptions[$i]) {
echo " selected='true'";
}
echo " value=" . $industryOptions[$i] . ">" . $industryOptions[$i] . "</option>";
}
?>
那么你的问题是什么?如何以更好的方式编写代码?我的问题是“有什么可以用更好的方式解决这个问题吗?”我得到了三元运算符作为答案,这正是我所需要的。:)谢谢完美地工作
<?php
$numberOfIndustries = count($industryOptions); //industryOptions is an array
for($i = 0; $i <= $numberOfIndustries; $i++) {
echo "<option" . ((isset($_POST['test']) == true && $_POST['test'] == $industryOptions[$i]) ? "selected='true'" : "") . "value=" . $industryOptions[$i] . ">" . $industryOptions[$i] . "</option>";
}
?>