Comments are notes written inside a program to explain the code. PHP ignores comments during normal execution, so they do not appear in the output. Comments help developers understand, maintain, and debug programs.
// and #, and multi-line comments using /* ... */.
A comment is text in the source code that explains what the program does. It is intended for developers and is not executed as PHP code.
<?php
// This is a comment
echo "Hello World!";
?>
The comment explains the code, while the echo statement displays the message.
The double slash (//) starts a single-line comment. PHP ignores the text after it until the end of the line.
<?php
// Display a welcome message
echo "Welcome to PHP";
// Display a second message
echo "<br>";
echo "Keep Learning!";
?>
Use // when you want to explain a statement or add a short note.
PHP also supports the hash symbol (#) for single-line comments.
<?php
# Store the student's name
$name = "Rahul";
# Display the student's name
echo $name;
?>
Both // and # can introduce single-line comments. The // style is commonly used in PHP examples.
Multi-line comments begin with /* and end with */. They are useful when an explanation needs more than one line.
<?php
/*
This program displays a message.
It is an example of a multi-line comment.
*/
echo "Learning PHP Comments";
?>
Everything between the opening and closing comment markers is treated as a comment.
You can write a comment on the same line after a PHP statement. The statement executes, but the comment is ignored.
<?php
$name = "Amit"; // Store the name
echo $name; // Display the name
?>
This style is useful for short explanations, but avoid writing excessively long comments beside statements.
During testing, you may temporarily comment out a statement to prevent it from executing.
<?php
echo "First Message";
// echo "This message is commented out";
echo "<br>";
echo "Second Message";
?>
The commented-out statement does not execute. Remember to remove temporary comments when they are no longer needed.
| Feature | Single-Line | Multi-Line |
|---|---|---|
| Syntax | // or # |
/* ... */ |
| Purpose | Short explanations | Longer explanations |
| Can span multiple lines? | No, each line needs a new marker | Yes |
| Executed as PHP code? | No | No |
<?php
// Single-line comment
# Another single-line comment
/*
Multi-line comment
for a longer explanation.
*/
echo "Comments make code easier to understand.";
?>
// starts a single-line comment.# also starts a single-line comment./* ... */ creates a multi-line comment.Complete the following tasks:
//.#.echo statement.<?php
// Store the student's name
$name = "Rahul";
/*
Display the name
on the browser.
*/
echo $name;
?>
Replace Rahul with your own name and run the program on your PHP-enabled server.
1. Which symbol starts a single-line comment in PHP?
2. Which syntax creates a multi-line comment?
3. What happens to a PHP comment during normal execution?