PHP Echo / Print
Displaying output in PHP
📢 What is Echo and Print?
Echo and print are PHP statements used to display text, variables, and HTML on the screen. They are the most common ways to output data in PHP programming.
<?php
// Using echo
echo "Hello World!";
// Using print
print "Welcome to PHP!";
?>
Output:
Hello World!
Welcome to PHP!
Key Differences
Echo
Echo is faster and can output multiple strings separated by commas. It has no return value and is commonly used for displaying content.
<?php
echo "Hello", " ", "World!";
?>
Print is slightly slower and can only output one string at a time. It returns 1, so it can be used in expressions.
<?php
print "Hello World!";
?>
With Parentheses
Both echo and print can be used with or without parentheses, making them flexible for different coding styles.
<?php
echo("With parentheses");
print("Also works!");
?>
With Variables
Both statements can display variables and combine them with text using concatenation or direct insertion in strings.
<?php
$name = "John";
echo "Hello $name!";
?>
🔹 Using Echo
Echo is the most popular way to output data in PHP:
<?php
// Simple text
echo "Hello World!";
// Multiple strings
echo "Hello", " ", "World", "!";
// With variables
$name = "Alice";
echo "Welcome, $name!";
// With HTML
echo "<h1>My Heading</h1>";
echo "<p>This is a paragraph.</p>";
?>
Output:
Hello World!
Hello World!
Welcome, Alice!
My Heading
This is a paragraph.
🔹 Using Print
Print works similarly but with slight differences:
<?php
// Simple text
print "Hello World!";
// With variables
$age = 25;
print "I am $age years old.";
// Print returns 1
$result = print "This returns 1";
echo "<br>Result: $result";
// With HTML
print "<h2>Subheading</h2>";
?>
Output:
Hello World!
I am 25 years old.
This returns 1
Result: 1
Subheading
🔹 Outputting Variables
Display variables using echo or print:
<?php
$name = "Bob";
$age = 30;
$city = "New York";
// Method 1: Inside double quotes
echo "Name: $name, Age: $age, City: $city";
// Method 2: Concatenation with dot
echo "<br>Name: " . $name . ", Age: " . $age;
// Method 3: Multiple parameters (echo only)
echo "<br>", "Name: ", $name, ", City: ", $city;
?>
Output:
Name: Bob, Age: 30, City: New York
Name: Bob, Age: 30
Name: Bob, City: New York
🔹 Outputting HTML
Create dynamic HTML content with PHP:
<?php
$title = "My Website";
$content = "Welcome to my page!";
echo "<div style='border: 2px solid blue; padding: 10px;'>";
echo "<h1>$title</h1>";
echo "<p>$content</p>";
echo "</div>";
?>
Output:
My Website
Welcome to my page!