How to Use of echo in PHP

Roshan Parmar Feb 02, 2024
  1. echo VS print in PHP
  2. Using echo or print in PHP
  3. Using PHP Echo Shorthand or Separate HTML
  4. Use of Echo in PHP
How to Use of echo in PHP

Echo is a language construct rather than a function in PHP.

In other words, it is not a function. It can be used to return a value or print output.

As a result, you won’t need to use parentheses. But you must use parentheses if you wish to use more than one parameter.

Now have a look at this with a syntax. The syntax of echo in PHP is given below:

void echo ( string $arg1 [, string $... ] )

The following are some important key elements to remember.

  • The echo statement is useful to display the output like string. It returns void.
  • Both are accepted in PHP, echo() and echo can be used with or without parentheses.
  • The echo command returns void. Many strings can be separated by a comma (,).
  • The echo command is quicker than the print function.
  • The echo command can be used many times because its functionality is easy to understand.
  • It is also the most usable command of PHP. There are two main methods for getting output in PHP: echo and print. The echo and print are the same. Both have the main work of displaying the output on the screen

echo VS print in PHP

You need to return the output or void in output; then, you can use the echo command.

The echo can accept many parameters like a string, escaping characters, and variable values. But the print function takes only one parameter.

The echo command is quicker than the print function. The echo command is the most important in PHP.

The following example explains how to use the echo command to print text:

<?php
echo "<h1>PHP is scrpting language </h1>";
echo "Hello world /n";
echo "A ", "group ", "charater ", "makes ", "string";
?>

Output:

PHP is a scripting language.
Hello world
A group character makes string.

Using echo or print in PHP

In PHP, you may use echo or print to show HTML markup, JavaScript, text, or variables.

Sample Code:

<?php
echo "<h1>PHP is scrpting language </h1>";
echo "Hello world /n";
 
echo "A ", "group ", "charater ", "makes ", "string";
?>

Output:

PHP is a scripting language.
Hello world
A group character makes string.

Using PHP Echo Shorthand or Separate HTML

You may use PHP echo shorthand to show the result of every expression, the value of every variable, or HTML markup.

Sample Code:

<?php 
    $name = "Hello world";
?>
 
<?= "<h1>Hello PHP,</h1>
    <h1>{$name} welcomes you</h1>" ?>

Output:

Hello PHP,
Hello, the world welcomes you.

Use of Echo in PHP

Printing String

Sample Code:

<?php
 
echo "Hello world  by PHP "; 
 
?> 

Output:

Hello world  by PHP

Printing Variable Value

<?php 
 
$s="Hello world  by PHP."; 
 
echo "Variable: $s";  
?>

Output:

Variable: Hello world  by PHP

Related Article - PHP Echo