Skip to main content

PHP Comments

By SamK
0
0 recommends
Category(s)
Topic(s)

A comment in PHP code is a line that is not executed as part of the program. Its only purpose is to be read by someone reviewing the code.

Comments can be used to:

  1. Help others understand your code
  2. Quickly remind yourself of what you did in the code
  3. Exclude certain parts of your code for testing and troubleshooting

PHP supports several ways of commenting.

// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */

Single Line Comments

Single-line comments start with //.

Any text between // and the end of the line will be ignored (will not be executed).

You can also use # for single-line comments, but // notation is most commonly used.

The following example uses a single-line comment as an explanation.

A comment before the code:

// Outputs a text message:
echo 'This is a text message';

A comment at the end of a line:

echo 'This is a text message'; // Outputs a welcome message

Comments to Ignore Code

Comments can be used to prevent code lines from being executed. This is particularly useful if:

  • You want to temporary hide any code line for troubleshooting
  • You want to test different versions of the code for any functionality

For example:

// echo "Welcome Home!";

Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

/*
The next code line will
print a text statement.
*/
echo "This is a text statement.";

The multi-line comment syntax can also be used to prevent execution of parts within a code line.

$x = 10 /* + 15 */ + 10;
echo $x;

The above example will output 20.

Questions & Answers