← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 6 of 13

PHP Comments

Single-Line Comments

A // or # comment tells PHP to ignore everything from that point to the end of the line. They're best for short, single-line notes — flagging a workaround, or reminding yourself why a value is hardcoded — rather than for explaining large blocks of logic.

Example: Single-Line Comments

php
<?php
// This is a single-line comment
# So is this
echo "Comments above are ignored";
?>

Multi-Line Comments

A /* ... */ comment can span multiple lines, making it the right tool for longer explanations: describing what a function does, documenting expected parameters, or temporarily annotating a tricky algorithm before you forget your own reasoning.

Example: Multi-Line Comments

php
<?php
/*
 * This function doubles a number.
 * Spans multiple lines to explain the logic.
 */
echo 5 * 2;
?>

Documenting Code

The most useful comments explain *why* a piece of code exists in a non-obvious form — a workaround for a browser quirk, a business rule that isn't visible from the code alone — rather than restating *what* the code does, which the code itself already shows.

Example: Documenting Code

php
<?php
// Workaround: legacy API returns price in cents, so we divide by 100
$price = 1999 / 100;
echo $price;
?>

Commenting Out Code

Wrapping a line (or block) in comment markers is a fast way to disable code temporarily while debugging, without deleting it outright. It's a normal part of the debugging workflow, but commented-out code left behind in a shipped file tends to rot and confuse the next reader.

Example: Commenting Out Code

php
<?php
echo "This line runs.\n";
// echo "This line is disabled while debugging.\n";
echo "This line also runs.\n";
?>

Comment Best Practices

Comments that don't match the code anymore are worse than no comment at all, because they actively mislead. Keep comments short, keep them focused on non-obvious intent, and update or delete them the moment the code they describe changes.

Example: Comment Best Practices

php
<?php
// Calculates the discounted price
function discount($price) {
    return $price * 0.9;
}
echo discount(100);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.