Learn

Short lessons with real code you can edit and run on the page.

Comments in PHP

Lesson 7 PHP 8.5 Runs in your browser
In short

Start a PHP comment with // or # for one line, or put it between /* and */ for several lines. PHP skips comments when it runs a script, so they never show up in the output. A one-line comment ends at the end of its line or at a ?> tag, whichever comes first.

Key facts

  • PHP runs PHP code inside an HTML comment, <!-- -->, and sends the comment to the browser.
  • One block comment can't hold another, because PHP ends a block comment at the first */ it finds.
  • Since PHP 8.0, #[ starts an attribute instead of a comment.
  • A DocBlock opens with /** and a space, tab or line break, and PHP keeps it with the declaration below it so code can read it later.
  • PHP prints a note written above <?php as plain text, because it isn't a PHP comment.

How do you write a comment in PHP?

Start a one-line comment with // or #, and put a longer one between /* and */. A comment is a note for people who read the code, and PHP ignores it.

PHP
<?php
// One ticket costs 12.
$price = 12;

# Three friends are going.
$tickets = 3;

/* Multiply the price by the number of tickets
   to get the total for the group. */
$total = $price * $tickets;
echo "Total: $total\n";
Output
Total: 36

PHP read all three comments and skipped them, which is why the output holds only the total. The // and # styles make single-line comments, and /* */ makes a multi-line comment, also called a block comment.

One-line and block comments end in different places, which changes how much code each kind can hide.

PHP comment syntax
SyntaxWhat it isWhere it ends
//One-line comment, C++ styleAt the end of the line or at ?>
#One-line comment, Unix shell styleAt the end of the line or at ?>
/* */Block comment, C styleAt the first */
/** */DocBlock, kept with the function or class after itAt the first */
#[Name]Not a comment but an attribute, since PHP 8.0At the matching ]

A block comment can also sit inside a line of code, between the parts of an expression. PHP reads 12 /* ticket */ + 3 as 12 + 3.

PHP
<?php
$total = 12 /* ticket */ + 3 /* booking fee */;
echo $total;
Output
15

A one-line comment can follow code on the same line, as in echo 12; // ticket. Inside a string, though, //, # and /* are ordinary text, and echo "https://www.php.net/"; prints the whole address.

Comments that visitors post under an article are a different topic. Our commenting system tutorial builds a comment section like that with PHP, MySQL and AJAX.

How do you comment out code in PHP?

Put // in front of a line of code to switch it off. For several lines, wrap them in /* and */. Remove the markers and the code runs again.

PHP
<?php
$price = 20;
// $price = $price - 5;
echo "Price: $price\n";
/*
echo "Sale price: " . ($price - 5) . "\n";
echo "Sale ends Friday\n";
*/
echo "Done\n";
Output
Price: 20
Done

PHP skipped the line that lowers the price and both lines in the block, so the price stayed at 20. Commenting out helps while you test a change, because the old code stays where it was.

In VS Code, Ctrl+/ (Cmd+/ on a Mac) adds // in front of the code on every selected line, and the same keys take the markers away again. Use // on every line when the code you switch off already contains a block comment.

Can you nest block comments in PHP?

No. PHP ends a block comment at the first */ it finds, even when another /* opened in between. Whatever follows that */ is code again, and a leftover */ there is a parse error.

PHP
<?php
/*
echo "Step 1\n";
/* echo "Step 2\n"; */
echo "Step 3\n";
*/
echo "Done\n";
Output

Parse error: syntax error, unexpected token "*", expecting end of file in /app/main.php on line 6

The comment that line 2 opens closes at the */ on line 4, which leaves the */ on line 6 outside any comment. Not even Done appears, because PHP finds a parse error before it runs anything.

The same thing happens when the code you comment out contains */. The pattern photos/*/thumb.jpg, which the glob() function uses to list matching files, holds a */ that ends the comment early.

PHP
<?php
/*
$photos = glob('photos/*/thumb.jpg');
*/
echo "Done\n";
Output

Parse error: syntax error, unexpected string content ");" in /app/main.php on line 3

The error looks unrelated to the comment because PHP reads the rest of line 3, after the early */, as code. A // at the start of the line avoids the problem, because a one-line comment ignores any /* or */ on its line.

PHP
<?php
// $photos = glob('photos/*/thumb.jpg');
echo "Done\n";
Output
Done

What happens when a PHP block comment is never closed?

PHP stops with an Unterminated comment error when a /* has no */ after it. The message names the line where that comment starts.

PHP
<?php
echo "Start\n";
/* Tax still needs adding.
echo "End\n";
Output

Parse error: Unterminated comment starting line 3 in /app/main.php on line 3

The PHP validator flags a /* that no */ ever closes. A missing */ is harder to find when another block comment comes later, because the first comment then runs on to that comment's */.

PHP
<?php
/* Every order ships for 5.
$shipping = 5;
/* Orders over 50 get a free gift. */
$order = 60;
echo "Total: " . ($order + $shipping) . "\n";
Output

Warning: Undefined variable $shipping in /app/main.php on line 6
Total: 60

The comment from line 2 swallowed $shipping = 5;, so $shipping never got a value and the total came out as 60 instead of 65. The warning names line 6, but the fix is a */ at the end of line 2.

Why does a one-line comment stop at ?> in PHP?

A ?> tag switches PHP off, even in the middle of a one-line comment. PHP outputs everything after the tag as plain text, the same way it treats text after any other closing ?> tag.

PHP
<?php
// Type ?> to leave PHP mode.
echo "Done\n";
Output
 to leave PHP mode.
echo "Done\n";

The comment ended at ?>. PHP then printed the rest of line 2 and the code on line 3 as text. On a website, that code would end up in the page that visitors receive.

A block comment doesn't stop at ?>, because it ends only at */. Use /* and */ for any note or line of code that contains ?>.

PHP
<?php
/* Type ?> to leave PHP mode. */
echo "Done\n";
Output
Done

Do HTML comments stop PHP code from running?

No. PHP doesn't treat <!-- and --> as a comment, so it outputs them as text and runs any PHP between them.

PHP
<p>Welcome</p>
<!-- <?php echo "Draft text"; ?> -->
Output
<p>Welcome</p>
<!-- Draft text -->

A browser doesn't display an HTML comment, but the comment still reaches the visitor, and anyone can read it in the page source. To hide PHP code, comment it out inside the PHP tags.

PHP
<p>Welcome</p>
<?php // echo "Draft text"; ?>
<p>Thanks for visiting</p>
Output
<p>Welcome</p>
<p>Thanks for visiting</p>

Nothing from the PHP comment reaches the output. The line break right after ?> disappears too, which is why the two paragraphs sit on neighboring lines.

Is #[ a comment in PHP 8?

No. Since PHP 8.0, #[ starts an attribute, so a # comment that begins with [ is no longer a comment.

An attribute is a label in square brackets that adds information to a function, class or other declaration. A note such as #[todo] was a plain comment before PHP 8.0, and PHP now reads it as an attribute.

PHP
<?php
#[todo] Check the tax rate.
echo "Done\n";
Output

Parse error: syntax error, unexpected identifier "Check" in /app/main.php on line 2

PHP read #[todo] as an attribute and then found the word Check, which can't follow one. Put a space after the #, or use //, and the note is a comment again.

PHP
<?php
# [todo] Check the tax rate.
// #[todo] is fine inside a // comment.
echo "Done\n";
Output
Done

Right above a function, #[todo] causes no error at all. PHP attaches it to the function as an attribute named todo, so the note quietly stops being a comment. The PHP 8.0 migration notes list this change.

What is a DocBlock in PHP?

A DocBlock is a block comment that starts with /** and describes the code right below it. It's also called a doc comment or a PHPDoc comment.

A function is a named piece of code that runs when you call its name, and functions get their own lessons later in the course. In a DocBlock above a function, tags such as @param and @return describe what the function takes and what it gives back.

PHP
<?php
/**
 * Adds the booking fee to a ticket price.
 *
 * @param int $price The ticket price.
 * @return int The price with the fee added.
 */
function withFee($price)
{
    return $price + 3;
}

echo withFee(12);
Output
15

The DocBlock doesn't change what withFee() does. PHP doesn't check its tags either, so @param int won't stop a call that passes text instead of a number.

What reads a DocBlock in PHP?

Your code can read a DocBlock through Reflection, the part of PHP that inspects code. PHP keeps a DocBlock that sits above a function or class for this, while other comments are gone once PHP has read the file.

PHP
<?php
/** Adds the booking fee. */
function withFee($price)
{
    return $price + 3;
}

/* Adds the sales tax. */
function withTax($price)
{
    return $price * 1.2;
}

var_dump((new ReflectionFunction('withFee'))->getDocComment());
var_dump((new ReflectionFunction('withTax'))->getDocComment());
Output
string(28) "/** Adds the booking fee. */"
bool(false)

Each var_dump() line asks PHP for the DocBlock of one function. The new keyword creates a ReflectionFunction helper for the function named in the quotes, and -> calls one of the helper's methods, the functions that belong to it.

The getDocComment() method returns the DocBlock, or false when there is none, as for the plain /* comment above withTax().

A DocBlock also needs a space, tab or line break right after /**, which is why PHP treats /**Adds the fee.*/ as a plain comment.

Code that reads DocBlocks while it runs needs PHP to keep them. OPcache, the part of PHP that keeps compiled scripts in memory, throws DocBlocks away when its opcache.save_comments setting is off, which can break that code.

The PHP minifier can strip comments from a file, and its Keep docblocks option leaves DocBlocks in place for code that reads them.

PHP 8.6 adds DocBlocks for individual function parameters, read with a new getDocComment() method of ReflectionParameter. The runner can't run that feature, because it uses PHP 8.5.12, which doesn't have the method.

Do comments slow down PHP?

Comments add no time once a script is running. PHP leaves them out of the instructions it compiles, and in our PHP 8.6.0 test, reading 2,000 comment lines added less than 0.2 milliseconds to loading the file.

What should a comment in PHP say?

A good comment says why the code does something, since the code already shows what it does. // Take 5 off. repeats the code under it, while // Members get 5 off. tells the reader something the code can't.

Update a comment when you change the code it describes, because a wrong comment misleads the next reader. Once you're sure you won't need commented-out code, delete it before old lines pile up.

Common mistakes with comments in PHP

In most PHP comment mistakes, the comment ends somewhere other than you meant.

  • Parse error: syntax error, unexpected token "*", expecting end of file. A block comment sits inside another one, so its leftover */ is read as code. Comment out each line with // instead.
  • Parse error: Unterminated comment starting line 3. The /* on the line the message names has no */. Add one where the comment should end.
  • Part of a comment, or the code after it, shows up in the output. A // or # comment contains ?>, which switched PHP off. Use /* and */ for that note.
  • A comment above <?php shows up in the output. Comments work only inside the PHP tags, and PHP outputs any text before <?php as it is. Move the comment below the tag.

Exercise

Comment out the line that prints Discount: 5 without deleting it. The script should then print Price: 20 and Total: 15. Also add a comment below <?php that says what $price holds, on the line above $price = 20; or at the end of that line.

PHP
<?php
$price = 20;
$discount = 5;
echo "Price: $price\n";
echo "Discount: $discount\n";
echo "Total: " . ($price - $discount) . "\n";
Output
Show the solution
<?php
// The price of one item before the discount.
$price = 20;
$discount = 5;
echo "Price: $price\n";
// echo "Discount: $discount\n";
echo "Total: " . ($price - $discount) . "\n";

Quiz

This quiz has 5 questions. Pick an answer to see why it is right or wrong.

  1. 1What does this script print?

    <?php echo "a"; // note ?>b
  2. 2What does this script print?

    <?php
    echo 1 + /* 2 + */ 3;
  3. 3What happens when this script runs?

    <?php
    /*
    echo "A\n";
    /* echo "B\n"; */
    */
    echo "C\n";
  4. 4What does this script print?

    <!-- <?php echo "Hi"; ?> -->
  5. 5Inside a PHP block, which of these lines is a comment in PHP 8.6?

Frequently asked questions

How do you comment out multiple lines in PHP?
Put the lines between /* and */, or start each line with //. A /* */ comment ends at the first */ it meets, so use // on each line when the code already contains */ or a block comment.
What are the three types of comments in PHP?
PHP has three comment types, // and # for one line and /* */ for a block. A one-line comment ends at the end of its line or at ?>, and a block comment ends at the first */. A DocBlock starts with /** and a space, tab or line break, and PHP keeps it with the function or class after it.
Which languages use the same comment styles as PHP?
PHP comments follow C for /* */, C++ for // and Unix shells for #. The # style is also called Perl style, and all three styles can appear in the same PHP file.
What is the shortcut to comment out PHP code in VS Code?
In VS Code, press Ctrl+/ on Windows or Linux, or Cmd+/ on a Mac. It adds // in front of the code on each selected line of PHP, and the same keys take it away again. Shift+Alt+A on Windows wraps the selection in /* and */ instead.
Can visitors see PHP comments?
No, PHP comments aren't sent to visitors. PHP skips them while it runs the script, and only the output reaches the browser. HTML comments are different, because the browser receives them and anyone can read them in the HTML source.
Does // inside a string start a comment in PHP?
No, comment markers inside quotes are part of the string. A string such as https://www.php.net/ prints in full, slashes included, and the same goes for # or /* inside a string.
Can a PHP comment go in the middle of a line of code?
Yes, a /* */ comment can sit between the parts of a statement. PHP reads 12 /* ticket */ + 3 as 12 + 3. A // or # comment can follow code too, but it hides the rest of the line up to any ?> tag.