Skip to main content

Comments in PHP

Comments are notes in your code that PHP skips when it runs the program. Their main job is to explain what the code is doing for whoever reads it next, and you can also use them to switch off code for a while.

PHP offers two kinds: single-line comments and multi-line comments.


Single Line Comments

You begin a single-line comment with either // or #. From that marker to the end of the line, PHP ignores everything and does not run it.

A comment before the code

Here a // comment sits on its own line above the code:

Prompt
Write a PHP script that uses a single-line comment with // before an echo statement. The comment should say "This is a single-line comment" and the echo should output "Hello World!".
Output: PHP script

A comment at the end of a line

A // comment can also follow the code on the same line:

Prompt
Write a PHP script that uses a single-line comment with // at the end of a line. Use echo to output "Hello World!" and add a comment "This is a single-line comment" at the end of the same line.
Output: PHP script

Using # for comments

The # marker works in the same way as //:

Prompt
Write a PHP script that uses a single-line comment with # before an echo statement. The comment should say "This is a single-line comment" and the echo should output "Hello World!".
Output: PHP script

Comments to Ignore Code

Commenting is also a quick way to stop a line from running without deleting it:

Ignore a line of code

Putting // in front of the first echo disables it, so only the second message appears:

Prompt
Write a PHP script with two echo statements. Comment out the first echo "Hello World!" using // so it does not execute, and leave the second echo "Have a good day!" active.
Output: PHP script