I suspect it's not allowable because I am getting "Parse error: syntax error, unexpected T_IF in..." error. But I couldn't find a way to accomplish my goal. Here's my code:
<?php     $countries = $myaddress->get_countries();    foreach($countries as $value){     echo '<option value="'.$value.'"'.if($value=='United States') echo 'selected="selected"';.'>'.$value.'</option>';   }   ?>   What it does is it displays a list of countries in a select element and sets United States as the default. I doesn't work sadly...
echo is a statement, which is used to display the output. echo can be used with or without parentheses: echo(), and echo. echo does not return any value. We can pass multiple strings separated by a comma (,) in echo.
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"; } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With