Reputation: 169
I've tried every combination I could think of, but nothing is working. How do I integrate an IF statement within a string?
This is the line I need integrated;
if ($row['SL'] == 'Yes') {echo '<li class=\"sl\">Short Sale</li>' ;}
This is what I tried;
elseif ($row['X'] == 'sold') { echo "
<li id=\"price\"> $ {$row['SP$']}</li>
" .
{ if ($row['SL'] == 'Yes') {echo '<li class=\"sl\">Short Sale</li>' ;} }
. "
<li>Days on Market: {$row['DOM']}</li>;
}
Upvotes: 1
Views: 74
Reputation: 12689
What you are looking for is called Ternary Operator or Shorthand If/Else:
( condition ? true result : false result )
Example:
echo "<li id=\"price\">{$row['SP']}</li>" . ( $row['SL'] == 'Yes' ? '<li class="sl">Short Sale</li>' : '' ) . "<li>Days on Market: {$row['DOM']}</li>";
The above example is the same as:
echo "<li id=\"price\">{$row['SP']}</li>";
if ( $row['SL'] == 'Yes' ) echo '<li class="sl">Short Sale</li>';
else echo '';
echo "<li>Days on Market: {$row['DOM']}</li>";
You can "stack" ternary expressions so the complete example will look like:
echo
$row['X'] == 'sold'
? "<li id=\"price\">{$row['SP']}</li>" .
( $row['SL'] == 'Yes' ? '<li class="sl">Short Sale</li>' : '' ) .
"<li>Days on Market: {$row['DOM']}</li>"
: '';
important: you cannot build a ternary operator without else statement.
Upvotes: 0
Reputation: 80639
Use a ternary operator:
elseif ($row['X'] == 'sold') { echo "
<li id=\"price\"> $ {$row['SP$']}</li>
" . ($row['SL'] == 'Yes') ? '<li class="sl">Short Sale</li>' : ''
. "
<li>Days on Market: {$row['DOM']}</li>";
}
Upvotes: 3
Reputation: 239311
You don't. You output the first half the string, then fully stop that statement, then evaluate your if
, then output the rest of the string.
...
elseif ($row['X'] == 'sold') {
echo "<li id=\"price\"> $ {$row['SP$']}</li>";
if ($row['SL'] == 'Yes') {
echo '<li class=\"sl\">Short Sale</li>'
}
echo "<li>Days on Market: {$row['DOM']}</li>";
}
You can't "embed" an if
statement in a string, firstly because that's not syntactically valid, but even if it was, if
statements don't resolve to a value in PHP.
Upvotes: 0
Reputation: 7330
You just need to break it up:
elseif ($row['X'] == 'sold') {
echo "<li id=\"price\"> $ {$row['SP$']}</li>";
if ($row['SL'] == 'Yes') {
echo '<li class=\"sl\">Short Sale</li>';
}
echo "<li>Days on Market: {$row['DOM']}</li>;
}
Upvotes: 2