Reputation: 2295
I have a menu with 3 options, that in the simplest form looks like:
<form action="samePageAction" form="post">
<select>
<option>Yes</option>
<option>No</option>
<option>Maybe</option>
</select>
</form>
It isn't really "dynamic", its just based on a user's setting in the database, I'm choosing what "option" to display by default:
<form action="samePageAction" form="post">
<select>
<?
if(!$personUndecided && $personHasAgreed){
?>
<option>Yes</option>
<option>No</option>
<option>Maybe</option>
<?
} else if(!$personUndecided && !$personHasAgreed){
?>
<option>No</option>
<option>Yes</option>
<option>Maybe</option>
</select>
<?
else {
?>
<option>Maybe</option>
<option>Yes</option>
<option>No</option>
</select>
<? } ?>
</form>
The "first" option in each case is important, because when the form is disabled, that is the option the user will see. I feel gross when I look at this, but a better solution isn't coming to me. How can I optimize this menu?
Question: How can I prevent repeating myself this much. Or does this code look perfectly normal?
Upvotes: 1
Views: 55
Reputation: 36
Something like this ?
<form action="samePageAction" method="post">
<select>
<?php
$possAnswer = array(
"1" => "<option>Yes</option>",
"0" => "<option>No</option>",
"2" => "<option>Maybe</option>"
);
if($personHasAgreed) {
echo $possAnswer[1] . $possAnswer[0] . $possAnswer[2];
} else if(!$personHasAgreed ){
echo $possAnswer[0] . $possAnswer[1] . $possAnswer[2];
} else {
echo $possAnswer[2] . $possAnswer[1] . $possAnswer[0];
}
?>
</select>
</form>
`
Upvotes: 0
Reputation: 92854
Simple solution with explode
function:
<form action="samePageAction" form="post">
<select>
<?php
$personHasAgreed = "";
$valueString = ($personHasAgreed === 1)? "Yes,No,Maybe" : (($personHasAgreed === 0)? "No,Yes,Maybe" : "Maybe,Yes,No" );
$valueString = explode(",", $valueString);
foreach($valueString as $word){
echo "<option>". $word ."<option>";
}
?>
</select>
</form>
Upvotes: 1
Reputation: 11689
You can short your code in this way, i.e.:
<?php
if( $personHasAgreed ) $choices = array ( 'Yes', 'No', 'Maybe' );
elseif( !$personHasAgreed ) $choices = array ( 'No', 'Yes', 'Maybe' );
else $choices = array ( 'Maybe','Yes', 'No' );
foreach( $choices as $choice ):
?>
<option><?php echo $choice; ?></option>
<?php endforeach; ?>
In this way you assign first the various choice values depending on $personHasAgreed
setting, then perform one foreach
loop to output each option.
Edit: please note that I think the else
statement will never be executed...
Upvotes: 1