Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if block inside echo statement?

Tags:

php

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

like image 433
Joann Avatar asked Aug 17 '10 21:08

Joann


People also ask

What is the use of echo statement?

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.


2 Answers

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>'; 
like image 191
Jim Avatar answered Sep 24 '22 03:09

Jim


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"; } 
like image 40
Frxstrem Avatar answered Sep 25 '22 03:09

Frxstrem