0

My code is working but I would like to know how can I make it more elegant instead of repeating whole <tr> content.

Here's the code:

<?php if($condition == true) { ?>
            <tr>
                <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                    <td>
                        content
                    </td>
                <?php endforeach; ?>
            </tr>
        <?php } else { ?>
            <?php foreach ( $attributes as $attribute_name => $options ) : ?>
                <tr>
                    <td>
                       content
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php } ?>

So, if condition is true, whole <tr> needs to be outside of the foreach loop, otherwise it needs to be inside of it. How can this be done without repeating the content ?

Tahi Reu
  • 558
  • 1
  • 8
  • 19

1 Answers1

1

I feel you have the an elegant way to achieve this without further changing the structure that you need, however, as an alternative, you could use a few if's depending on what the result of condition is, which will stop the need to repeat the content, and help you to maintain DRY standards.

if($condition) { 
  echo '<tr>';
}

foreach ( $attributes as $attribute_name => $options ) {
  if(!$condition) { 
    echo '</tr>';
  } else { 
    echo '<td>';
  }

  //content

  if($condition) { 
    echo '</td>';
  } else { 
    echo '</tr>';
  }

}

if($condition) { 
  echo '</tr>';
}

You could also use ternary (How to write a PHP ternary operator) condition:

echo ($condition) ? '</tr>' : '';

foreach ( $attributes as $attribute_name => $options ) {
  echo (!$condition) ? '<tr>' : '<td>';

  //content

  echo (!$condition) ? '</tr>' : '</td>';

}

echo ($condition) ? '</tr>' : '';
Adam
  • 1,294
  • 11
  • 24
  • Thank you. Ternary solution is pretty nice. I actually had the DRY solution on my mind but it still seemed to me that there is too much unnecessary code there. – Tahi Reu Apr 17 '19 at 16:02