PHP Comments

La Lakshmi Priya Updated 17 Oct 2026
9 min read ·Lesson 19 of 22

What Is a Comment?

In simple terms: A comment is a note inside your code that PHP ignores. It is written for people, not for the computer.

Technically: A comment is a section of source code that the PHP parser skips while compiling the script. Comments produce no opcodes, no output, and have no effect on how the program runs.

Why Comments Exist

Code tells PHP what to do. It does not always tell the next developer why it does it that way. Comments fill that gap. They are used to:

  • Explain the reason behind a decision or a non-obvious piece of logic
  • Warn about side effects, limitations, or edge cases
  • Document functions and classes for other developers and for tools
  • Temporarily disable code while testing or debugging
  • Mark unfinished work (TODO) or known problems (FIXME)

The "next developer" is very often you, a few months later.


Types of Comments in PHP

SyntaxTypeEnds At
// commentSingle-line (C++ style)End of the line, or ?>
# commentSingle-line (shell style)End of the line, or ?>
/* comment */Multi-line (C style)The first */
/** comment */Documentation comment (DocBlock)The first */

This lesson focuses on single-line comments. Multi-line comments and DocBlocks are covered in the PHP Multiline Comments lesson.


Single-Line Comments With //

Syntax

// This is a comment

Everything from // to the end of the line is ignored.

Example

<?php
// Calculate the final price after a discount
$price = 1000;
$discount = 15; // percentage

$finalPrice = $price - ($price * $discount / 100);

echo $finalPrice; // prints 850

Output

850

How It Works

  • Line 2 is a full-line comment. It describes what the next block of code does.
  • // percentage on line 4 is an end-of-line comment. PHP runs $discount = 15; and ignores everything after //. It clarifies the unit of the value — without it, a reader might wonder whether 15 means ₹15 or 15%.
  • The comment after echo is ignored the same way.

The script produces exactly the same output with or without its comments.


Single-Line Comments With #

Syntax

# This is also a comment

# works exactly like //. It comes from Unix shell scripts and Perl, which influenced early PHP.

Example

<?php
# Configuration
$maxLoginAttempts = 5;
$lockoutMinutes = 15; # how long an account stays locked

echo "Lockout after $maxLoginAttempts failed attempts.";

Output

Lockout after 5 failed attempts.

// or # — Which Should You Use?

Both are valid, but // is the standard choice in modern PHP code. Most coding standards and frameworks use //, and using one style consistently makes code easier to scan.

There is also a technical reason to be careful with #:

#[ Is Not a Comment Since PHP 8.0

PHP 8.0 introduced attributes, which use the syntax #[...]:

<?php
#[Deprecated]
function oldFunction() {}

Because of this, a line beginning with #[ is parsed as an attribute, not as a comment. Code from PHP 7 such as:

<?php
#[TODO] refactor this function

was a harmless comment in PHP 7 but is a syntax error in PHP 8. If you use # comments, always put a space after the #. Attributes are covered in the PHP Attributes lesson.


Comments and the Closing Tag

Single-line comments end at the end of the line or at a closing ?> tag, whichever comes first.

Example

<p>Status: <?php echo "Active"; // show status ?> (updated daily)</p>

Output

<p>Status: Active (updated daily)</p>

Why This Happens

PHP stops the comment at ?> and returns to output mode, so (updated daily)</p> is sent to the browser normally. This behavior allows single-line comments inside short inline PHP blocks in templates.

The flip side is a surprising bug: a ?> written inside a comment still ends PHP mode.

<?php
// Close the tag with ?> when the file contains HTML
echo "This line is printed as text, not run";

Output

 when the file contains HTML
echo "This line is printed as text, not run";

The comment ends at ?>, so everything after it is treated as plain output — including the code on the next line. Avoid writing ?> inside single-line comments. Multi-line comments (/* ... */) do not have this problem.


Comments in PHP vs Comments in HTML

PHP files often contain both PHP and HTML, and both languages have comments. They behave very differently.

Example

<!-- HTML comment: the visitor can see this in View Source -->
<?php
// PHP comment: removed on the server, never sent
$apiKey = "sk_live_123"; // secret key — never print this
?>
<p>Hello</p>

Output (HTML received by the browser)

<!-- HTML comment: the visitor can see this in View Source -->
<p>Hello</p>
AspectPHP Comment (//, #, /* */)HTML Comment (<!-- -->)
Processed byPHP engine on the serverThe browser
Sent to the browser?NoYes
Visible in View Source?NoYes
Affects page size?NoYes — adds bytes to every response
Suitable for internal notes?YesNo

Warning: Never put internal notes, credentials, server paths, or details about known bugs in HTML comments. Anyone can read them by viewing the page source. Use PHP comments for anything meant only for developers.

An HTML Comment Does Not Disable PHP

<!-- <?php deleteAllRecords(); ?> -->

This does not stop the PHP code. PHP runs on the server first and does not understand HTML comments. deleteAllRecords() executes, and only its output ends up inside the HTML comment. To disable PHP code, use PHP comments.


Commenting Out Code While Debugging

Comments are commonly used to disable lines temporarily to find where a problem comes from.

Example

<?php
$subtotal = 2000;
$tax = $subtotal * 0.18;
// $discount = applyCoupon($subtotal);
$discount = 0;

$total = $subtotal + $tax - $discount;
echo $total;

Output

2360

How It Is Used

The developer suspects applyCoupon() is returning a wrong value. By commenting out the call and using a fixed value instead, they can confirm whether the rest of the calculation is correct. Most editors toggle comments with Ctrl + / (or Cmd + / on macOS).

Best practice: Remove commented-out code before committing it to version control. Old code left in comments confuses readers ("Is this still needed? Why was it disabled?"), and version control such as Git already keeps the history if you need it back.


Writing Useful Comments

Not all comments are helpful. The most valuable comments explain things the code cannot express by itself.

Comment the "Why", Not the "What"

Not useful — repeats what the code already says:

<?php
// Add 1 to $retries
$retries = $retries + 1;

Useful — explains the reason:

<?php
// The payment gateway sometimes returns a timeout even when the payment
// succeeds, so we retry with the same transaction ID instead of a new one.
$retries = $retries + 1;

The first comment adds nothing — anyone who can read PHP sees that $retries increases. The second contains knowledge that is not visible in the code and prevents a future developer from "fixing" the logic in a way that would charge customers twice.

Prefer Clear Names Over Explanatory Comments

<?php
// Check whether the user is an adult
if ($a >= 18) {
    // ...
}

A better variable name removes the need for the comment:

<?php
if ($userAge >= 18) {
    // ...
}

Code changes over time, and comments are easy to forget to update. A comment that disagrees with the code is worse than no comment at all. Clear names stay accurate because they are part of the code.

Explain Non-Obvious Values

<?php
$sessionLifetime = 1800; // 30 minutes, in seconds
$maxFileSize = 5 * 1024 * 1024; // 5 MB in bytes

Units and the meaning of "magic numbers" are among the most useful things to comment. An even better solution is often a named constant, such as const MAX_UPLOAD_BYTES = 5 * 1024 * 1024;, which is covered in PHP Constants.

Warn About Consequences

<?php
// WARNING: this file is included by the cron job and the website.
// Do not output anything here, or session headers will fail.

TODO and FIXME Markers

Developers often use standard keywords in comments to mark work that still needs attention.

<?php
// TODO: add pagination when the product list grows beyond 100 items
$products = getAllProducts();

// FIXME: rounding is wrong for amounts with more than 2 decimals
$total = round($amount, 2);
MarkerMeaning
TODOPlanned work that has not been done yet
FIXMEKnown bug or incorrect behavior that must be fixed
HACKA temporary workaround that should be replaced with a proper solution
NOTEImportant information for anyone reading the code

Editors such as PhpStorm and VS Code (with extensions) can list every TODO and FIXME in a project, making them easy to track. For anything important, also create an issue in your project's task tracker, since comments are easy to overlook.


Do Comments Affect Performance?

No measurable effect. PHP discards comments while compiling the script into opcodes, so they are never executed. With OPcache enabled (the standard on production servers), compilation happens once and the cached opcodes contain no comments at all.

Never shorten or remove meaningful comments to "speed up" code. The only exception is DocBlock comments, which OPcache keeps by default because some libraries read them at runtime — this is explained in the PHP Multiline Comments lesson.


Common Mistakes

Writing ?> Inside a Single-Line Comment

What happens: Code after the comment is printed as text instead of being executed.

Fix: Do not use ?> in // or # comments, or use a /* */ comment instead.

Starting a Comment With #[

What happens: In PHP 8+, the line is parsed as an attribute and causes a syntax error or unexpected behavior.

Fix: Use //, or put a space after #.

Using HTML Comments to Hide PHP Code

What happens: The PHP code still runs; only its output is wrapped in an HTML comment.

Fix: Use PHP comments to disable PHP code.

Exposing Sensitive Information in HTML Comments

What happens: Notes such as <!-- admin panel at /secret-admin --> are visible to anyone.

Fix: Use PHP comments for internal notes.

Outdated Comments

What happens: The code is changed but the comment is not, so the comment now describes behavior that no longer exists.

Fix: Update or delete comments whenever you change the code they describe. Treat comments as part of the code during reviews.


Best Practices

  • Use // for single-line comments consistently.
  • Explain why, not what; let clear names describe the what.
  • Document units, magic numbers, and non-obvious business rules.
  • Keep comments short and accurate, and update them with the code.
  • Remove commented-out code before committing.
  • Never place secrets or internal details in HTML comments.

Official reference: https://www.php.net/manual/en/language.basic-syntax.comments.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Comments and get answers drawn from it.

Signed-in readers only.