How to Use echo in PHP: Simple Syntax and Examples
In PHP, use the
echo statement to output text or variables directly to the browser. It is simple to use by writing echo followed by the text or variable you want to display, ending with a semicolon.Syntax
The basic syntax of echo is simple. You write echo followed by the text or variable you want to show. You can use quotes for strings and separate multiple items with commas.
- echo: The command to output content.
- Text or variables: What you want to display.
- Semicolon (;): Ends the statement.
php
echo "Hello, world!"; echo $name; echo "Hello", " ", "world!";
Example
This example shows how to use echo to print a simple message and a variable's value.
php
<?php $name = "Alice"; echo "Hello, world!"; // prints Hello, world! echo "\n"; // new line for clarity echo "Hello, ", $name, "!"; // prints Hello, Alice! ?>
Output
Hello, world!
Hello, Alice!
Common Pitfalls
Some common mistakes when using echo include forgetting the semicolon, mixing quotes incorrectly, or trying to use parentheses like a function.
Remember, echo is a language construct, not a function, so parentheses are optional but can cause confusion.
php
<?php // Wrong: missing semicolon // echo "Hello world" // Wrong: mixing quotes // echo 'Hello" world'; // Right: correct quotes and semicolon echo "Hello world"; // Right: parentheses optional echo("Hello again");
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Output string | Prints text to the screen | echo "Hello!"; |
| Output variable | Prints variable value | echo $name; |
| Multiple items | Prints several items separated by commas | echo "Hi", " ", $name; |
| With parentheses | Optional parentheses around items | echo("Hello"); |
Key Takeaways
Use
echo to output text or variables in PHP.Always end
echo statements with a semicolon.You can output multiple items separated by commas without concatenation.
echo is a language construct, so parentheses are optional.Be careful with quotes and syntax to avoid errors.