Categories
php

if block inside echo statement?

66

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…

    174

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

    5

    • 3

      So that’s where ternary operator is useful. That was quick, thanks a lot!

      – Joann

      Aug 17, 2010 at 21:27

    • Its not “my preference” in situations like this. I like the ternary operator for defaulting / setting variables. But given that is what you asked, there is how you do it 🙂

      – Jim

      Aug 17, 2010 at 21:28

    • 2

      It’s a ternary operator but not the ternary operator (although I don’t know any other ternary operator). Another common term is conditional operator.

      – Gumbo

      Aug 18, 2010 at 6:05


    • Yea an easily overlooked mistake on my part. Fixed it Gumbo.

      – Jim

      Aug 18, 2010 at 13:09

    • ‘.(($value==’United States’)?’selected=”selected”‘:””).’ can also be value=”‘.(($value==”)?’ selected ‘:””).’ the first is supposedly XHTML but just using ‘selected’ should work just fine. Is a bit simpler.

      – timpng1

      Mar 14 at 23:12

    19

    You can always use the ( <condition> ? <value if true> : <value if false> ) syntax (it’s called the ternary operatorthanks 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";
    }
    

    1

    • As @Gumbo pointed out, this is just one ternary operator, not “the”. “Another common term is conditional operator.”

      – strager

      Aug 18, 2010 at 13:10

    9

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