PHP Comments

2 min read

Comments in PHP are not executed by the PHP interpreter but skipped automatically. They serve as programmers to make your code easier to understand. You can, as the name says, comment on your program code, that is, explain what functions individual sections of the program have.

Defining comments in PHP

To insert a comment in a PHP script, you can either use two slashes (//) or a hash symbol (#). If one of these two characters appears on your program code, the rest of the contents of the line will be skipped, and the PHP interpreter will move to the next line.

<?php
echo "Hello World! <br>"; // This is a comment
#Another comment - Outputting the text
echo "As you can see, the comments are not visible on the output result.";
?>

Everything after a double slash or the hash is ignored. The newline then terminates the comment and the code in the next line are executed again.

Multi-line comments

Sometimes it makes sense to have a comment over several lines, for example, if you want to comment out a program section.
Such a comment starts with / * and ends with * /:

<?php 
/* The first line of the comment 
Second line of the comment 
The last line of the comment */ 
echo "Hello world, as you can see, only this text will be displayed, the comments in the front are not visible."; 
?>

What and how should one comment?

Comments allow you as a programmer to comment on the functionality of your scripts. You are not obliged to use them, but they can help you enormously to make your code clearer and easier to understand.

You should always comment on what your script does, rather than how it does it. It's recommended to comment on the functionality so that when you re-study the program code, it quickly becomes clear what exactly individual sections of the code are doing.

« »