Is this method to Output HTML good or bad?

Hello folks, sort of a newbie to this here. I have the following question regarding the code below:



<?php

function output_html(){ ?>
    <div>hello world</div>
<? php}

output_html();

?>


Is this a bad practice? Can it have any repercussions whatsoever?

Thanks for your help.

Andres.

Well, it’s pretty unreadable, which is bad.

You could do something similar to:-


<?php
function say_hello(){
  return '<div>Hello World</div>';
}
?>
<html>
  <head>
    <title>Foo</title>
  </head>
  <body>
    <?php echo say_hello(); ?>
  </body>
</html>

There’s a million and one ways to do this sort of thing, just find one you’re comfortable with and try to stick with it. :wink:

And I would not recommend to use short php tags <?..?> any more to be compatible with new PHP versions!

Thanks folks for the quick reply!

I will illustrate a bit further what I am trying to do so that you may direct me in approaching this problem in the right way.


<?php 

function output_categories($categories){
	foreach($categories as $cat){
		output_category($cat);		
	}
}

function output_category($cat){ global $counter; $counter++;?>
	
		<li class='level-<?php echo $cat->level +1 ?>'>
		<?php if(isset($cat['subcats'])): ?>
			<div class='expandable'>+</div>
		<?php endif; ?>	
			<p><?php echo $cat['name'] ?><span>&nbsp;(<?php //echo $categories->countPics($cat['id']) ?>)</span></p>
		
			<?php if(isset($cat['subcats'])): ?>
				<ul>
					<?php output_categories($cat['subcats']) ?>
				</ul>		
			<?php endif; ?>		
		</li>
<?php  } ?>

<ul>
	<?php output_categories($categories->cats);?>
</ul>




The reason why I wanted to format it this way is to maintain HTML readability.
I could return HTML as a string but that is gonna hinder the HTML readability. So the function output_category(); will act as a template that may contain quite a lot of html. How could I go about this in a more clever or organized way?

Thanks again for your input.

Andres.

As Anthony already told that there is not a specific way specified by PHP itself. So as far as I know there will not be any issues/problems in your way too. You can just use one that is comfortable for you and stick on that always so that one standard is maintained. And yes indeed sometimes outputting HTML in your way is better even you can still construct the HTMLs within PHP strings (heredoc, etc.). So no problem with your way too (Y).

Thanks Raju! BTW Kathmandu is a very interesting place. Want to go back some time.

You are always welcome Andres! Yes we have a beautiful city here… :slight_smile: