I have no idea really how to say this, but I can demonstrate it:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
vs
<?php if (true) { ?>
<h1>Content Title</h1>
<?php } ?>
What differences are there between the two? Will there be problems caused by not using echo? It just seems super tedious to write echo "html code"; all the time, specially for larger segments of html.
Also, bonus kudos to someone who can rephrase my question better. :)
There's a small difference between the two cases:
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
Here, because you're using double quotes in your string, you can insert variables and have their values rendered. For example:
<?php
$mytitle = 'foo';
if (true) {
echo "<h1>$mytitle</h1>";
}
?>
Whereas in your second example, you'd have to have an echo enclosed in a php block:
<?php if (true) { ?>
<h1><?php echo 'My Title'; ?></h1>
<?php } ?>
Personally, I use the same format as your second example, with a bit of a twist:
<?php if (true): ?>
<h1><?php echo $mytitle; ?></h1>
<?php endif; ?>
I find that it increases readability, especially when you have nested control statements.
There are no relevant differences performance-wise. But you won't be able to use variables in the latter, and it looks less clean IMO. With large blocks, it also becomes extremely difficult to keep track of {}
structures.
This is why the following alternative notation exists:
<?php if (true): ?>
<h1>Content Title</h1>
<?php endif; ?>
it's marginally more readable.
This:
<?php if (true) : ?>
<h1>Content Title</h1>
<?php endif; ?>
This is the way PHP is supposed to be used.
Don't echo
HTML. It's tedious, especially because you have to escape certain characters.
There may be slight performance differences, with the above probably being faster. But it shouldn't matter at all. Otherwise, no differences.
I appreciate all the feedback. :)
I did find out some issues when using the two different methods.
There does not appear to be any real issue here except that the formatting looks terrible on the source and the tedious nature of it.
<?php
if (true) {
echo "<h1>Content Title</h1>";
}
?>
Using php this way can cause an error as such
Warning: Cannot modify header information - headers already sent
<?php if (true) { ?>
<h1>Content Title</h1>
<?php } ?>
The headers error can possibly be solved by using php like so
<?php ob_start(); if (true) { ?>
<h1>Content Title</h1>
<?php } ob_end_flush(); ?>
As to why and when the headers are sent, I am not completely sure...