Skip to main content

A comment in PHP code is a line that is not executed as a part of the program. Its purpose is to let others understand your code and remind yourself of what you did, yes; it is possible that you are looking at your code after an year or two and you forget little or more about your own code.  Commenting is often used for quick notes about complex and confusing code or to temporarily remove a line of PHP code. So, using comment is one of the best practice of writing code. PHP supports 2 types of comments:

  1. Single Line
  2. Multi-Line

1. PHP Single Line Comment

There are 2 ways to use single line comment in PHP

  • C++ style single line comment - //
  • Unix Shell style (Perl Style) single line comment - #

C++ style single line comment

We use // for c++ style comments. Example:

<?php  
// this is C++ style single line comment  
echo "Hello World!";  
?> 

Unix Shell style single line comment

The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment.

<?php  
# this is Unix Shell style single line comment  
echo "Hello World!";  
?> 

2. PHP Multi Line Comments

Multi lines comments are enclosed within /* */. All text that appears between the start of the comment and the end will be ignored.

<?php  
/* 
This
is 
multi
line
comment
*/  
echo "Hello World!";  
?>  

Points to remember

1. Using comment to leave out parts of code:

<?php
    $x = 10 /* + 30 */ + 20;
    echo $x;
?>

2. Comment can also used to hide your code, example:

<h1>This is an<?php # echo 'simple';?> example</h1>

Here simple will not be printed. Output will be This is an example.

3. Don't nest comments

It is easy to make this mistake if you are trying to comment out a large block of code.

<?php
 /*
    echo 'This is a test'; /* This comment will cause a problem */
 */
?>

Do read user notes here to see how comments can make your life easy and typical sometimes.

Tags
Submitted by tgoswami on June 15, 2021

Tarun has 10+ years of experience in Quality Assurance in different domains like banking, e-commerce, health and education.

About

Elix is a premium wordpress theme for portfolio, freelancer, design agencies and a wide range of other design institutions.