PHP echo statement: In PHP, the echo statement is used to output text or HTML content to a web page. It’s commonly used to display dynamic content, such as variables, database query results, or HTML code generated by a PHP script.
The echo statement has a few key points to consider, and I’ll explain them with examples
Usage of echo Statements
You can display the plain text
<?php echo "Hello, CodinStatus!"; ?>
You can display the values of variables.
<?php $name = "CodingStatus"; echo $name; ?>
You can display multiple items, separated by commas.
echo "Name: ", "Nurullah", ", Age: ", 28;
You can display the value of a variable with text
<?php $name = "Alice"; echo "Hello, $name!"; ?>
You can embed PHP variables within double-quoted strings using curly braces {}.
$name = "CodingStatus";
echo "Hello, {$name}!";
You can display HTML content.
<?php echo "<h1>Welcome to my website</h1>"; echo "<p>This is a paragraph.</p>"; ?>
You can display attributes within HTML tags.
$url = "https://example.com";
echo "<a href='{$url}'>Visit Example</a>"; // Outputs a link
Best Practices
Here are the key best practices for using echo in PHP with examples
Separation of Concerns
Keep PHP logic separate from HTML presentation.
<?php $name = "Alice"; echo "Hello, $name!"; ?>
Good
<?php
$name = "Alice";
?>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello, <?= $name ?>!</h1>
</body>
</html>
Double Quotes for Interpolation
Use double quotes for variable interpolation in strings.
$name = "Bob"; echo 'Hello, $name!'; // Single quotes won't interpolate variables
Good
$name = "Bob"; echo "Hello, $name!"; // Double quotes allow variable interpolation
Short Echo Tags
Use <?= ... ?> for simple variable embedding in HTML.
$message = "Welcome!"; ?> <div><?= $message ?></div>
Output Logic Separately
Use echo for output, not complex logic.
Bad
echo ($is_logged_in) ? "Welcome, User!" : "Please log in.";
Good
$msg = ($is_logged_in) ? "Welcome, User!" : "Please log in."; echo $msg;
Translation and Localization
Use PHP’s localization functions for translation.
echo "Welcome";
Good
echo _("Welcome");
Try Yourself
- Write a PHP script that uses the
echostatement to display the text “Hello, World!” on the web page. - Create a PHP script that declares a variable
$namewith your name and then usesechoto display a greeting message, like “Hello, [Your Name]!”. - Write a PHP script that concatenates two variables,
$first_nameand$last_name, and usesechoto display a full name. - Create an HTML form that takes a user’s name as input and then uses PHP to display a greeting message using the
echostatement after the user submits the form. - Write a PHP script that uses
echoto generate HTML code for a simple table with two rows and two columns, and display it on the web page. - Display the current date and time using the
date()function in PHP and theechostatement.