Why do I echo for a single HTML tag? [closed]

0

I've noticed in a lot of php tutorials that they have separate html tags. For example:

echo "<h1>Datos extraidos:</h1>";
echo "<b>dato</b>";
echo "<b>Otro dato";

Why do not you place them in this way?:

echo "<h1>Datos extraidos:</h1> <br> <b>Dato</b> <br> <b>Otro Dato</b>"
    
asked by Flavio C. Siria 02.08.2017 в 04:28
source

2 answers

1

That depends on the programmer.

Let's see some examples and usual practices.

PHP + HTML by blocks

In PHP files that combine with HTM content, you can open HTML-only segments, especially when you have to place a lot of HTML-only content.

To do this, the PHP tag is closed and the HTML code is written directly:

<?php

código php ...

?>

<h1>Esto es todo HTML</h1>
    <p>Lorem ipsum</p>
    ... más contenido HTML
    <p>Ya abriremos de nuevo PHP</p>

<?php
... sigue código PHP

In your example you could proceed like this, placing all HTML content in a block of HTML only:

<h1>Datos extraídos</h1>
    <p><b>Dato:</b> texto de dato.</p>
    <p><b>Otro dato:</b> texto de otro dato</p>

HTML + PHP with loops

One possibility is this:

<ul>
<?php foreach ($users as $user) { ?>
    <li><?php echo $user->name ?></li>
<?php } ?>
</ul>

Another possibility is concatenating a variable:

Here we would always stay in PHP, without combining. Provide a more readable code:

<?php
$html="<ul>";

foreach ($users as $user) {
    $html.="<li>".$user->name."</li>";
}
 $html.="</ul>";

echo $html;
?>

Conclusion

These are just some possibilities. As it has been said, it is about code legilibity.

It's more if you want you can make code like this:

<?php echo "L" ?> 
o 
<?php echo "r" ?> 
e 
<?php echo "m" ?>

I hope you do not decide for this last possibility:)

    
answered by 02.08.2017 в 04:50
0

Imagine you have the code:

echo "<li>One</li><li>Two</li>><li>Three</li><li>Four</li>";

In general, a more complex one takes time to read and sometimes it is hard work, now imagine if:

echo "<li>One</li>";
echo "<li>Two</li>";
echo "<li>Three</li>";
echo "<li>Four</li>";

It is more readable, which makes it easier to find errors and help other programmers to understand it better, for example in an open source where several people have to read it.

Also, if you mention that you have seen it in tutorials, it is for those who see it to understand it better.

    
answered by 02.08.2017 в 04:53