So I'm trying to generate select values with a loop. The issue here is that I can't use an if statement. I could set pieces of string together with a number of if statements, but that seems like an odd solution.
<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>
You cannot use the .
(dot) to concat IF
clause - only strings. Instead, you can use the ternary operator.
So your echo
call should look as follows:
echo "<option " .
(isset($_POST['test']) && ($_POST['test'] == $industryOptions[$i]) ? "selected='true' " : "").
"value=" . $industryOptions[$i] . ">" . $industryOptions[$i] . "</option>";
Just echo separately instead of creating one huge statement that is impossible to read.
<?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>";
}
?>
However, if you really want to use a one line statement there is a thing called conditional ternary operator
which allows you to do what you want to do.
<?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>";
}
?>