if block inside echo statement?
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
You can always use the ( <condition> ? <value if true> : <value if false> )
syntax (it's called the ternary operator - thanks to Mark for remining me :) ).
If <condition>
is true, the statement would be evaluated as <value if true>
. If not, it would be evaluated as <value if false>
For instance:
$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";
This is the same as:
$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
echo "Fourteen is more than twelve";
}else{
echo "Fourteen is not more than twelve";
}
Use a ternary operator:
echo '<option value="'.$value.'"'.($value=='United States' ? 'selected="selected"' : '').'>'.$value.'</option>';
And while you're at it, you could use printf
to make your code more readable/manageable:
printf('<option value="%s" %s>%s</option>',
$value,
$value == 'United States' ? 'selected="selected"' : ''
$value);