DEV Community

Mateusz Jasiński
Mateusz Jasiński

Posted on

PHP echo tag - A simple solution to common problem

Hi, what's up? If you ever coded in PHP, you definitely had created a code as simple as this

<?php
    echo "Some more or less important info";
?>
Enter fullscreen mode Exit fullscreen mode

It takes us as much as 3 lines - it's not a lot but while writing my PHP course and consuming the docs I've encountered this

PHP includes a short echo tag <?= which is a short-hand to the more verbose <?php echo.

I thought - "Huh, let's give it a try". And it worked, so that's why I write this article

A little bit of info

This short echo tag is in standard and is not a part of some library/framework. And by the way it's not classified as short tag

So even if short_open_tag is disabled, this tag still works

But, let's test it

Short echo tag in practice

So, syntax for this tag looks like this

<?= "Text to display" ?>
Enter fullscreen mode Exit fullscreen mode

When I checked it - I wrote this

<?=  "Hello short echo tags" ?>
Enter fullscreen mode Exit fullscreen mode

And it worked

working short echo tag

(Don't think about the size, I purposefully made this text bigger with browser scaling)

But, does it allow use to use multi-line echo? Can we do something like this?

<?=  
    "Hello short echo tags
    Hi"
?>
Enter fullscreen mode Exit fullscreen mode

Yes, we can!

Many lines

But maybe a variable?

<?php 
    $var = 5;
?>

<?=  
    $var
?>
Enter fullscreen mode Exit fullscreen mode

Variable

It still works!

And last test - a function + variable

<?php 
    $var = "password";
?>

<?=  
    password_hash($var, PASSWORD_DEFAULT)
?>
Enter fullscreen mode Exit fullscreen mode

Function inside that tag

No problem with that too

So, it successfully managed to pass all of the tests

Conclusion

When I discovered this tag, my first thought was to write article about it. And when I found time - that's how this article was born

I hope you learned something new and useful, that this will help you with your work

Check out my other articles and series such as

That's it, see you in next articles

Top comments (0)