PHP Comments: A Complete Guide with Examples
PHP comments are an essential part of writing readable, organized, and maintainable PHP code. They allow developers to add explanations, describe the purpose of a program, document functions, and temporarily disable code during testing. PHP ignores comments during normal program execution, so they do not directly affect the output of a PHP script.
Understanding PHP comments is important for beginners as well as experienced developers because well-written comments make programs easier to understand, debug, update, and maintain.
What Are PHP Comments?
PHP comments are notes written inside PHP source code to explain how the code works or why a particular approach is used. They are intended for developers and are not executed as PHP instructions.
PHP supports three commonly used comment styles:
- Single-line comments using
// - Single-line comments using
# - Multiline comments using
/* */
Each style serves a particular purpose, depending on the length and nature of the explanation.
Example of a PHP Comment
<?php
// Display a welcome message
echo "Welcome to PHP!";
?>Output:
Welcome to PHP!In this example, // Display a welcome message is a comment. PHP ignores it and executes the echo statement to display the welcome message.
Types of PHP Comments
1. Single-Line Comments Using //
The double-slash symbol (//) is the most common way to write a single-line comment in PHP. Everything after // on that line is treated as a comment until the end of the line or the end of the PHP block.
This comment style is useful for explaining a statement, describing a variable, or clarifying a short section of code.
Example:
<?php
// Store the user's name
$name = "Rahul";
// Display the name
echo $name;
?>Output:
RahulIn this example, the comments explain the purpose of the variable and the output statement. They help readers understand the code without changing its behavior.
You can also place a short comment after a statement.
<?php
$price = 500; // Product price
$quantity = 2; // Number of products
echo $price * $quantity;
?>Output:
1000Inline comments should remain short and should not make the code difficult to read.
2. Single-Line Comments Using #
PHP also supports the hash symbol (#) for single-line comments. Its behavior is similar to the // comment style.
Example:
<?php
# Calculate the total marks
$math = 85;
$english = 90;
$science = 80;
$total = $math + $english + $science;
echo $total;
?>Output:
255The # symbol tells PHP to ignore the remainder of the current line as a comment.
Although both # and // are valid, // is generally preferred in modern PHP projects because it is widely recognized and consistent with many programming languages.
3. Multiline Comments Using /* */
Multiline comments begin with /* and end with */. Everything between these two markers is treated as a comment.
They are useful when an explanation requires multiple lines, such as describing a calculation, outlining a feature, or documenting a complex section of code.
Example:
<?php
/*
This program calculates the total price
of a product based on its price and quantity.
*/
$price = 250;
$quantity = 4;
$total = $price * $quantity;
echo $total;
?>Output:
1000Multiline comments can contain several lines of text, making them suitable for longer explanations.
PHP does not support nested block comments. Therefore, placing another /* ... */ block inside an existing block comment can cause unexpected parsing errors.
PHP Comments Inside Conditional Statements
Comments can be used inside conditional statements to explain the purpose of a condition or the action performed when the condition is true or false.
Example:
<?php
$age = 20;
// Check whether the person is eligible to vote
if ($age >= 18) {
echo "Eligible to vote";
} else {
echo "Not eligible to vote";
}
?>Output:
Eligible to voteThe comment describes the condition without affecting the program’s decision-making process.
PHP Comments Inside Loops
Loops are often used to repeat instructions. Comments can explain what a loop processes or why a particular condition is necessary.
Example:
<?php
// Display numbers from 1 to 5
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>Output in a web browser:
1
2
3
4
5The comment describes the purpose of the loop. It is especially helpful when loops involve complex conditions or multiple operations.
PHP Comments for Temporarily Disabling Code
Developers sometimes use comments to prevent a statement from executing while testing or debugging a program. This practice is known as commenting out code.
Example:
<?php
echo "First message";
// echo "Second message";
echo "Third message";
?>Output:
First message
Third messageThe second echo statement is ignored because it is commented out.
You can also disable a block of code with multiline comments:
<?php
echo "Program started";
/*
echo "Temporary message";
echo "Another temporary message";
*/
echo "Program finished";
?>Output:
Program started
Program finishedHowever, multiline comments should be used carefully when disabling code because PHP does not allow nested block comments. For longer sections of code, developers can comment out individual lines or use an editor’s comment functionality.
PHP Documentation Comments (PHPDoc)
PHPDoc comments are structured comments commonly used to document functions, methods, classes, parameters, return values, and exceptions. They usually begin with /** and end with */.
PHPDoc is particularly useful in professional PHP development because IDEs, documentation generators, and static-analysis tools can interpret these comments.
Example:
<?php
/**
* Calculates the total price of a product.
*
* @param float $price Price of one product
* @param int $quantity Number of products
* @return float Total price
*/
function calculateTotal(float $price, int $quantity): float
{
return $price * $quantity;
}
echo calculateTotal(150.50, 3);
?>Output:
451.5In this example:
/** ... */introduces a documentation comment.@paramdescribes a function parameter.@returndescribes the expected return value.- The function declaration specifies the parameter and return types.
PHPDoc comments are not the same as ordinary explanatory comments. Their structured format makes them useful for generating API documentation and improving code navigation.
PHP Comments and HTML Comments
PHP and HTML use different comment syntax. Understanding the difference is important when building websites that combine PHP with HTML.
PHP comments:
<?php
// This is a PHP comment
echo "Hello World";
?>HTML comments:
<!-- This is an HTML comment -->
<p>Hello World</p>PHP comments are interpreted by the PHP parser and do not appear in the generated HTML output. HTML comments are included in the output sent to the browser, although browsers do not display their contents as ordinary page text.
For example:
<?php
// This comment is not included in the HTML output
echo "<p>Hello World</p>";
?>The browser displays:
Hello World
The PHP comment does not become part of the generated page.
By contrast, an HTML comment written inside PHP output can be sent to the browser:
<?php
echo "<!-- This is an HTML comment -->";
echo "<p>Hello World</p>";
?>The HTML comment appears in the page source even though it is not displayed as visible text. Therefore, sensitive information should never be placed in HTML comments.
PHP Comments and JavaScript Comments
PHP and JavaScript both support // and /* ... */ comments, but they are interpreted in different execution environments.
Example:
<?php
// PHP comment
echo "Hello from PHP";
?>JavaScript example:
<script>
// JavaScript comment
console.log("Hello from JavaScript");
</script>PHP executes on the server, whereas JavaScript in a typical web application executes in the browser. A PHP comment is removed during PHP processing and is not sent as a comment to the browser. A JavaScript comment included in a script sent to the browser remains part of the delivered source code, even though the JavaScript engine ignores it.
Important Rules for Writing PHP Comments
When writing PHP comments, follow these important rules:
- Use
//for short, single-line explanations. - Use
/* ... */for explanations spanning multiple lines. - Use
/** ... */for PHPDoc documentation. - Keep comments clear, concise, and relevant to the code.
- Explain why a complicated operation is necessary instead of simply repeating what the code already says.
- Update comments whenever the related code changes.
- Avoid excessive comments that make code harder to read.
- Never store passwords, API keys, private tokens, or other sensitive information in comments.
- Do not rely on comments to disable security checks or bypass validation.
- Use consistent comment formatting throughout a project.
A good comment provides useful context. For example, // Apply a discount for orders above the minimum purchase amount is more informative than // Check condition when explaining a discount calculation.
Advantages of PHP Comments
PHP comments offer several benefits in software development.
Improved readability: Comments help developers understand the purpose of variables, functions, conditions, and complex operations.
Easier maintenance: When a program needs to be updated, clear comments can help developers identify the reasoning behind existing code.
Simplified debugging: Temporarily commenting out selected statements can help isolate errors during development.
Better teamwork: Comments allow developers to communicate implementation details and important decisions to other team members.
Improved documentation: PHPDoc comments help describe reusable functions, classes, parameters, and return values.
Reduced learning difficulty: Beginners can use comments to understand the structure and purpose of PHP programs.
Common Mistakes When Using PHP Comments
Using an Incorrect Closing Marker
A multiline comment must be closed with */.
Incorrect:
<?php
/* This comment is not closed
echo "Hello";
?>This code produces a parsing problem because the block comment is not properly terminated.
Correct:
<?php
/* This comment is closed correctly */
echo "Hello";
?>Writing Nested Block Comments
PHP does not support nested block comments.
Incorrect:
<?php
/*
Outer comment
/*
Inner comment
*/
echo "Hello";
*/
?>The inner closing marker terminates the first block comment, leaving the remaining text to be interpreted as PHP code and potentially causing a syntax error.
Writing Unnecessary Comments
Comments should add information rather than repeat obvious statements.
Less useful:
<?php
// Set age to 25
$age = 25;
?>More useful when context is needed:
<?php
// Minimum age required for this service
$minimumAge = 25;
?>The second example explains the meaning of the value instead of merely repeating the assignment.
Exposing Sensitive Information
Never include actual credentials or confidential data in source-code comments. Comments may become accessible through source repositories, deployment packages, or generated HTML if written in the wrong context.
PHP Comments in Web Development
PHP comments are useful in many types of web projects, including content management systems, e-commerce platforms, APIs, and custom web applications.
Developers may use comments to explain database queries, describe authentication logic, document API endpoints, clarify form validation, or record important implementation decisions.
Example:
<?php
// Validate the submitted email before processing the form
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($email !== false && $email !== null) {
echo "Valid email address";
} else {
echo "Please enter a valid email address";
}
?>The comment explains the purpose of the input validation. The actual validation is performed by filter_input(), not by the comment itself.
Comments improve understanding, but they do not make code secure by themselves. Security must be implemented through appropriate validation, authorization, parameterized database queries, and other relevant safeguards.
Best Practices for PHP Comments
For clean and maintainable PHP code, consider the following recommendations:
- Write comments when the purpose or reasoning behind the code is not immediately obvious.
- Prefer meaningful variable and function names alongside comments.
- Use PHPDoc for public functions, methods, and classes when structured documentation is beneficial.
- Keep temporary debugging comments out of production code when they are no longer needed.
- Avoid outdated explanations that contradict the current implementation.
- Follow the PHP coding standards adopted by your project.
- Remember that comments are intended for human readers and do not replace automated tests or technical documentation.
Frequently Asked Questions (FAQs)
1. What are comments in PHP?
Comments in PHP are explanatory notes written in source code. PHP ignores them during normal execution, so they do not directly affect the program’s output.
2. What are the three types of PHP comments?
The three commonly used comment styles are // for single-line comments, # for single-line comments, and /* ... */ for multiline comments.
3. How do you write a single-line comment in PHP?
Use either // or # before the comment text.
Example:
<?php
// This is a single-line comment
echo "Hello";
?>4. How do you write a multiline comment in PHP?
Place the comment between /* and */.
Example:
<?php
/*
This is a multiline comment.
It contains more than one line.
*/
echo "Hello";
?>5. Do PHP comments affect program execution?
PHP comments are ignored as PHP instructions. They do not directly change program behavior, although changing comment markers can affect how the parser interprets surrounding source code.
6. What is a PHPDoc comment?
A PHPDoc comment is a structured documentation comment that begins with /** and can include tags such as @param, @return, and @throws to describe code elements.
7. Can PHP comments be nested?
No. PHP block comments do not support nesting. An inner */ closes the current block comment.
8. What is the difference between PHP comments and HTML comments?
PHP comments are processed on the server and are not included in the generated output as PHP comments. HTML comments are sent to the browser as part of the HTML source but are not displayed as ordinary page text.
9. Can comments be used to disable PHP code?
Yes. You can comment out a single statement with // or #, or disable a block with /* ... */, provided the block-comment markers are used correctly.
10. Are PHP comments visible to website visitors?
PHP comments in PHP source code are normally removed during server-side processing. However, HTML comments generated by PHP can be visible in the browser’s page source. Never place confidential information in comments.
Conclusion
PHP comments are a simple but important feature that helps developers write readable, maintainable, and well-documented programs. PHP supports single-line comments using // and #, multiline comments using /* ... */, and structured documentation comments using PHPDoc syntax.
By choosing the appropriate comment style, documenting complex logic, avoiding unnecessary explanations, and keeping comments accurate, developers can improve code quality and make PHP projects easier to understand and maintain.