PHP Comments

A comment in php is a line or a couple of lines which is not executed by the php interpreter. PHP supports both single line comments and multi line comments. Comments are pretty useful when writing code in PHP.

Comments in PHP can be used to –

  • Let other people understand your code, or to remind yourself your own code if you are going to look at it after a long time.
  • To disable a part of code temporarily that is not in use.

Single line comment

A single line comment can be created by starting any statement with double forward slashes (//). This is like the C++ style comment.

For Example –

<?php
    $a = 1;
    //This will print the numbers from 1 to 5
    while($a <= 5)
    {
        echo $a;
        $a++;
    }
?>

A single line comment can also be created by hash(#) sign. This is like the Unix-shell style comment.

<?php
    $a = 1;
    #This will print the value inside a
    echo $a;
?>

Note : We have used a while loop in our examples. You need not to worry about it as of now. We will learn about  loops in a separate lesson.

Multiline Comments

A multiline comment starts with /* and ends with */.

<?php
    $a = 1;
    /*This loop will print the
numbers starting from
1 to 5*/
    while($a <= 5)
    {
        echo $a;
        $a++;
    }
?>

Using comments to disable a part of our code

<?php
    $a = 7;
    echo $a;
    /*$a = 12;
    echo $a;
    $a = 14;
    echo $a;*/
    $a = 16;
    echo $a;
?>

Advantages of using comments in PHP

  • Using comments in our PHP scripts, we can make people understand our code who are reading it.
  • We can temporarily disable a part of our code that is not required for any reason.
  • Comments can help a programmer to understand his own code seen after a long interval of time.

Tip: When using multi line comments, always remember to properly close the comment section by */ otherwise there  would occur errors running the script.