In this tutorial, you shall learn about comments in PHP, single line and multiline comments, and how to use them in programs with the help of examples.
Comments
Comments are part of the program that does not get executed, but are intended only for readability of the program.
In a PHP program, we can have single line comments, or multiline comments.
Single Line Comments
To define a single line comment, start the comment with double forward slash //
, or hash #
.
In the following, we have defined a comment starting with double forward slash.
PHP Program
<?php
$a = 10;
$b = 20;
//add the two numbers
$c = $a + $b;
echo $c;
?>
In the following, we have defined a comment starting with hash character.
PHP Program
<?php
$a = 10;
$b = 20;
#add the two numbers
$c = $a + $b;
echo $c;
?>
Multiple Line Comments
To define a multiple line comment, start the comment with /*
and end the comment with */
.
In the following, we have defined a multiple line comment.
PHP Program
<?php
$a = 10;
$b = 20;
/* add the two numbers
and assign the result
to a variable named c. */
$c = $a + $b;
echo $c;
?>
Comment in the line of code
After writing the code, we can specify the comment after that code, in the same line using single line comments or multiple line comments.
PHP Program
<?php
$a = 10; #this is a comment
$b = 20; //this is a comment
$c = $a + $b; /* this is also a comment */
echo $c;
?>
We can also write a comment in the middle of a program statement, using the syntax of multiple line comment.
PHP Program
<?php
$a = 10;
$b = /* $a + 5 */ 20;
$c = $a + $b;
echo $c;
?>
In the above program, /* $a + 5 */
is the comment.
Conclusion
In this PHP Tutorial, we learned how to write single or multiple line comments in a PHP program, with the help of examples.