PHP echo Statement

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.

Bad
<?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.

Bad
$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.

Bad
echo "Welcome";

Good

echo _("Welcome");

Try Yourself

  1. Write a PHP script that uses the echo statement to display the text “Hello, World!” on the web page.
  2. Create a PHP script that declares a variable $name with your name and then uses echo to display a greeting message, like “Hello, [Your Name]!”.
  3. Write a PHP script that concatenates two variables, $first_name and $last_name, and uses echo to display a full name.
  4. Create an HTML form that takes a user’s name as input and then uses PHP to display a greeting message using the echo statement after the user submits the form.
  5. Write a PHP script that uses echo to generate HTML code for a simple table with two rows and two columns, and display it on the web page.
  6. Display the current date and time using the date() function in PHP and the echo statement.