Comments
Learn to write single-line (//, #) and multi-line (/* */) comments in PHP.
Comments
Comments are used to add explanations to PHP code. PHP ignores comments when running; they do not affect the output.
There are three types: // for single line, # for single line (shell style), and /* */ for multi-line comments.
Example: // this is a note or /* this is also a note */.
Comments make code readable; they are especially useful for explaining complex logic.
Multi-line comments
In PHP, /* */ marks a multi-line comment. This type is ideal for explanations that span several lines.
Example: /* This comment spans two lines */
Multi-line comments cannot be nested: starting another /* */ inside one causes a PHP error.
You can also use multi-line comments to temporarily disable a piece of code.
Exercise Write a comment and echo
Write a PHP block. Add a single-line // comment. Then use echo to print "Welcome back"; add \n at the end of the line.
Show example solution
Write a // comment, then add echo "Welcome back\n";.
Example solution:
<?php
// greeting message
echo "Welcome back\n";
Test yourself
-
Which comment starts with the # sign?
- // comment
- /* comment */
- # comment
- <!-- comment -->
Show answer
# comment — Correct! A line starting with # is a comment.
-
Complete the comment line
<?php ____ echo "Welcome back"; ?>Show answer
<?php // greeting message echo "Welcome back"; ?> -
Match the comment types
- //
- C-style comment
- #
- Shell-style comment
- /* */
- Multi-line comment