Originally published on zero2php.dev — part of the Zero to PHP course. View this lesson on the original site.
Why comments exist
Comments are for humans (including future you). PHP ignores them at runtime.
Syntax
- Single-line:
//or# - Multi-line:
/* ... */
Example
<?php
declare(strict_types=1);
// Next line prints a greeting
echo "Hi\n";
/*
Multi-line comment:
explain *why* something non-obvious is here.
*/
What makes a good comment
Strong comments answer questions the code alone does not answer well:
- Why a non-obvious approach was chosen (performance, compatibility, a bug workaround).
- Constraints you must respect: time zones, encoding, API limits, “do not change without checking X”.
- Assumptions that would surprise a reader: “We expect at most one match; duplicates are a data bug.”
- Edge cases or gotchas the next person will hit when they “improve” the code.
They stay short, live next to the logic they clarify, and are updated when the code changes.
What tends not to help
- Restating the code in English (
// increment i) when the line is already obvious. - Noise that adds reading time without new information.
- Stale comments that contradict the code—readers may trust the comment and break things.
- Large blocks of commented-out old code left “just in case”; version control remembers history—delete or restore from git instead of leaving a graveyard in the file.
It is fine to leave no comment when names and structure already tell the story.
Examples: helpful vs weak
<?php
declare(strict_types=1);
// Weak: repeats what `strlen` obviously does.
$s = 'hello';
// Get the length of $s
$len = strlen($s);
// Better: explains a non-obvious choice (byte length vs character count for UTF-8 comes later).
// Length in bytes; not always the same as “number of characters” for UTF-8 strings.
$bytes = strlen($s);
<?php
declare(strict_types=1);
// Weak: narrates the next line.
// Set timeout to 30
$timeout = 30;
// Better: explains why this number exists.
// API hard-limits requests to 30s; higher values are ignored with a warning in their logs.
$timeout = 30;
<?php
declare(strict_types=1);
// Avoid: dead code kept as comments—delete it or recover it from version control.
// $old = computeLegacyTotal($items);
// return $old;
$total = array_sum($items);
Good style in one line
Prefer comments that explain intent, constraints, or why something surprising is correct—not a play-by-play of the next statement.
Exercise
Add a // comment (any text) on its own line, then set $total to the sum of 40 and 60, and echo $total so the output is 100.
From Zero to PHP — PHP foundations: environment, syntax, and values