if block inside echo statement?

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...


您将需要使用一个三元运算符,它充当缩短的IF / Else语句:

echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';

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);

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";
}
链接地址: http://www.djcxy.com/p/12010.html

上一篇: 如何在回声中嵌入if语句

下一篇: 如果块内部的回声陈述?