rockyraw rockyraw - 1 year ago 81
PHP Question

Condition inside a condition (short form)

I have the following condition, which says that if

, then an image will be created in the code:

<?= !$img[$i] ? "" : "<div class=\"image\"> <img src=\"/images/1.gif\" /></div>"; ?>

I want to add another condition that says that if
, then a class called
will be added to the image, so eventually code will look like:

<div class="image"><img src="images/1.gif" class="centered"/></div>

So basically this means putting another condition inside the previous condition, but I can't simply add
!$center ? '' : ' class="centered"'
in the middle of the code.

How can I achieve this?

Answer Source

Yes, you can 'put it in the middle':

<?= $img[$i] ? '<div class="image"> <img src="/images/1.gif"'.($center ? ' class="centered"' : '').' /></div>' : ''; ?>

But that is ugly, don't you agree? I now make the assumption you what to output the HTML code. Then I can rewrite your code into:

if ($img[$i]) {
  echo '<div class="image">'.PHP_EOL;
  echo '  <img src="/images/1.gif"'.($center ? ' class="centered"' : '').' />'.PHP_EOL;
  echo '</div>'.PHP_EOL;

I think that looks nicer, in the sense that it is easier to read.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download