My #1 Tip for PHP Programmers to Read and Write Code Easier
There’s a better way though.
Take a look at lines 1 to 15 below. It does the same as lines 20–32:
The second section is easier to read (and write!).
A web server ultimately evaluates all of the code and prints out HTML. It doesn’t matter if you write the HTML in, or out, of the <?php … ?> tags.
Why Is This So Good?
Sometimes it gets tricky when the HTML you want to print out has single or double quotes (ex. specifying a Link or a Style/CSS class).
I have two solutions for this:
- Start/end your statement with the opposite type of quote that you need
- “Escape” the data, by adding a slash right before the quote
Both of these are inconvenient 😜
The next comparison example shows a real-world example demonstrating it’s easier to read, especially because most editors will color-code the different HTML tags. Note the first example has two instances of printing out a link (each using a different method as described above).
This is the same code as above, but a screenshot from my editor (Sublime Text) that better shows the color-coding of HTML tags:
Printing HTML in PHP: A Best Practice
There’s a shortcut to printing out text, where you use an equal sign instead of the opening “PHP” tag. I suggest avoiding it though. Compare these two:
<?php // This works, but don't do it ?>
<?="Hello";?><?php // instead do this ?>
<?php print "Hello"; ?>
The reason to not use the first one is that, if you were read in an XML file without specifying “php” then you may get errors. XML files also have <? . It’s better to get in the habit of explicitly using <?php print… to display the text.
And yes, “echo” and “print” do the same thing in PHP.
Like this style of writing? 👍👍 Are you creating a PHP web application and already know what a “variable” is and the concept of an “if” statement? Check out my book: Web Development for Intermediate Programmers — with PHP