Use echo Shorthand in PHP

  1. Introduction to the echo Statement in PHP
  2. Substitute the echo Statement With the <?= ?> Shorthand Tag in PHP

This article will introduce the echo statement and discuss how to write the echo statement in shorthand in PHP.

Introduction to the echo Statement in PHP

The echo statement in PHP is used to display the output to the user. The print statement is also widely used to display the output. The echo statement can also be written with parenthesis as echo(). It can output multiple expressions, unlike print which can only output a single expression. It does not have any written value, and it is faster than the print statement.

In the example below, we have used the echo statement to display a simple text. We can also display the arithmetic operations with the echo statement. We have used the HTML <br> tags along with the echo statement. We have concatenated numbers along with the text while using the echo statement. We have also found out how we can write multiple expressions in the echo statement.

Example Code:

$num =2;
$num1 = 3;
$place = "tree";
echo "Hello there!<br>";
echo $num + $num1."<br>";
echo "There are ".$num. " birds in the ".$place."!<br>";
echo "It ", "is ", "raining ", "outside. ";

Output:

Hello there! 
5 
There are 2 birds in the tree! 
It is raining outside.

Substitute the echo Statement With the <?= ?> Shorthand Tag in PHP

We just learned about the echo statement. While working in PHP, we may have to use the HTML tags most often. We might want to use the PHP inside of HTML sometimes. In that case, we have to write the PHP opening tag <?php and the closing tag ?> every time we want to write PHP. Suppose we have to display something; we have to use the echo statement inside the PHP tags. It might become tedious to follow this approach every time.

So, instead of writing the echo statement inside the PHP tags, we can use the <?= ?> shorthand tag of the echo tag. It is pretty simpler and shorter than writing the echo statement inside the PHP tags. For example, let’s have a look at the following code snippet.

Example Code:

<?php
$name = 'Jack Grealish';
$age = 26;
?>

<p><?php echo $name ?></p>
<!--some codes -->
<p><?php echo ?></p>

We can write the above code using the shorthand as the following.

Example Code:

<?php
$name = 'Jack Grealish';
$age = 26;
?>

<p><?= $name ?></p>
<!--some codes -->
<p><?= $age ?></p>

Output:

Jack Grealish

26
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - PHP Echo

  • Add Line Break in PHP
  • Related Article - Echo Shorthand

  • Add Line Break in PHP