A comment is a part of the PHP code that is **not executed** as part of the program. Its main purpose is to be read by humans — either yourself in the future or other developers working on your project.
For short, one-line explanations, PHP supports two styles of comments: the double-slash
// (most common) and the hash # style.
<?php
// This is a single-line comment
echo "Hello World!";
# This is also a single-line comment
$x = 5;
?>
You can also place a single-line comment at the end of a line of code:
<?php
$sum = 10 + 20; // adding two numbers together
?>
When you need to write longer explanations or block out large sections of code, use the
/* ... */ syntax. Everything between these symbols will be ignored by
PHP.
<?php
/*
This is a multi-line comment.
It can span across
multiple lines easily.
*/
echo "Multi-line comments are great for long documentation.";
?>
/*
inside another /* */ block will cause a syntax error.
Comments are incredibly useful when you're trying to find a bug. By commenting out lines, you can isolate the code and see exactly where the problem lies.
<?php
$x = 5 + /* 10 + */ 5;
echo $x; // Outputs: 10
?>
$x = 5; // sets x to 5. Instead,
comment on the why behind the code, not the what.