-2

I've attempted to add an if/else statement within an already opened echo function, but page comes up blank. Not too sure if I am concatenating properly.

echo '<span class="year-tab-'.$x.' '.if ($single_year==$year_selected) { echo "" } else { echo "display-none" }.' ">';
John Conde
  • 217,595
  • 99
  • 455
  • 496
wharfdale
  • 1,148
  • 6
  • 23
  • 53

3 Answers3

5

You cannot have control structures inside concatenation

$style = ($single_year==$year_selected) ? '' : "display-none";
echo '<span class="year-tab-'.$x.' '.$style.'">';

That concatenation is a bit messy. printf() might be a bit cleaner

printf('<span class="year-tab-%s %s">', 
    %x,
    ($single_year==$year_selected) ? '' : "display-none"
);
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Actually, you can use ternary operator inside echo's, there's no need to use another variable in your first example (for readability would be better to use an if though) – hlscalon Oct 14 '14 at 00:51
3

Or you can do this:

echo '<span class="year-tab-'.$x.' '.($single_year==$year_selected ? "" : "display-none").' ">';

See Ternary Operator on this page.

Dwayne Towell
  • 8,154
  • 4
  • 36
  • 49
0

Using the ternary operator:

echo '<span class="year-tab-'.$x;
echo ($single_year==$year_selected)? '>' : ' style="display:none">';

Note that for display value, you have to enclose it inside the display tag.

DonMiguel
  • 11
  • 1