How and Why to Comment in Your PHP Code

Comments can save you and other programmers extra work later

Smiling young man working on computer
Neustockimages/E+/Getty Images

A comment in PHP code is a line that is not read as part of the program. Its only purpose is to be read by someone who is editing the code. So why use comments?

  • To let others know what you're doing. If you are working with a group of people or plan on anyone else ever using your script, the comments tell the other programmers what you were doing in each step. This makes it much easier for them to work with and to edit your code if needed.
  • To remind yourself what you did. Although you may just be writing a quick script for yourself and don't see the need for comments, go ahead and add them in anyway. Most programmers have experienced coming back to edit their own work a year or two later and having to figure out what they did. Comments can remind you of your thoughts when you wrote the code.

There are several ways to add a comment in PHP code. The first is by using // to comment out a line. This one-line comment style only comments to the end of the line or the current code block, whichever comes first. Here is an example:

 <?php 
 echo "hello"; 
 //this is a comment 
 echo " there"; 
 ?> 

If you have a single line comment, another option is to use a # sign. Here is an example of this method:

 <?php 
 echo "hello"; 
 #this is a comment 
 echo " there"; 
 ?> 

If you have a longer, multi-line comment, the best way to comment is with /* and  */ before and after a lengthy comment.

You can contain several lines of commenting inside a block. Here is an example:

 <?php 
 echo "hello"; 
 /* 
 Using this method 
 you can create a larger block of text 
 and it will all be commented out 
 */ 
 echo " there"; 
 ?> 

Don't Mix Comments

Although you can nest comments within comments in PHP, do so carefully.

Not all of them nest equally well. PHP supports C, C++ and Unix shell-style comments. C style comments end at the first */ they encounter, so don't nest C stye comments. 

If you are working with PHP and HTML, be aware that HTML comments mean nothing to the PHP parser. They won't work as intended and are likely to execute some function. So, stay away from: 

<!--Comment-->