3

Please refer the following two forms of the same code

First:

<?php if(some_condition){
?>
    <li><a target="_blank" href="example.com/channel1/"  class="xyz">If content</a></li>
<?php
}else{
?>
    <li><a target="_blank" href="example.com/channel2/"  class="xyz">Else Content</a></li>

<?php?>
}?>

Second :

<?php 
    if(some_condition){
       echo '<li><a target="_blank" href="example.com/channel1/"  class="xyz">If content</a></li>';
    }
    else{
        echo '<li><a target="_blank" href="example.com/channel2/"  class="xyz">Else Content</a></li>';
    }
 ?>

My question is which one of the following is a better option.I know the second one is more readable. But if there are so many conditions on the same page, then which is better performance-wise(i believe, there will be only a negligible performance difference between the two).

I would like to know your views/points, regarding standards performance and whatever you think I should know, about the two different forms.

(And which should be preferred over the other,when there is only single if-else block, and multiple if-else blocks)

Thanks

2

I would argue that the first example is the better of the two evils as it is more maintainable. The HTML is written as is, and not coded as a string literal.

Using templating or some other way to keep business logic and HTML presentation separate usually results in more maintainable code.

2

As always, the short and probably most correct answer: It depends.

To expand:

For the two snippets in that short as shown in the question it's purely about taste. There is no strong technical reason for one over the other. In a larger context the question is "are those rather HTML templates with a little logic in between or are those code parts with lot's of logic and a little of HTML?"

Of course if it's mostly logic, a good idea is to look into template library's like Twig or others and separate the logic from output in a larger degree, whcih allows testing and changing output formats more easily.

  • It is not recommended to echo HTML using PHP, due to performance. So even in this situation the first approach would be the preferred solution. – Andy Sep 22 '17 at 10:14
  • 1
    If you care that much about performance don't use PHP, but native code. For at least 99% of these cases readability and maintainability of the code is more relevant than a tiny potential performance difference (which can change from PHP version to PHP version and where I'm too lazy to think about as it's irrelevant) – johannes Sep 22 '17 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.