213

I've come across this PHP tag <?= ?> recently and I am reluctant to use it, but it itches so hard that I wanted to have your take on it. I know it is bad practice to use short tags <? ?> and that we should use full tags <?php ?> instead, but what about this one : <?= ?>?

It would save some typing and it would be better for code readability, IMO. So instead of this:

<input name="someVar" value="<?php echo $someVar; ?>">

I could write it like this, which is cleaner :

<input name="someVar" value="<?= $someVar ?>">

Is using this operator frowned upon?

Script47
  • 103
  • 5
marco-fiset
  • 8,721
  • 9
  • 35
  • 46
  • 12
    The problem with this kind of question is that it is so opinionated. There "technically" isn't a right or wrong way. Some argue for, some against, its all preference. So in the end its up to you. – mseancole Jun 05 '12 at 21:43
  • Avoid the closing tag in any form, if you can - i.e. the file contains only php code(no html etc). If you have a closing tag, any characters after it will be output to the browser (for a web app) - which can result in very hard to debug problems. For more : http://stackoverflow.com/a/4453835/49560 – simplfuzz Apr 22 '16 at 06:46
  • Non-opinion related: Watch out because `echo`leads very easily to XSS, and you should better rely on context-dedicated echoing method (ie: having a `function html($x) { echo htmlentities($x,...); }` and un `html($someVar);` instead of `echo $someVar` or using `echo json_encode($x);` for JS context). This then makes `=` tags a bad practice because it means you have HTML-escaped the variable content in another place, and so that other place must magically know this variable has to be HTML escaped because it's echoed in HTML context. – Xenos Mar 23 '19 at 12:48

8 Answers8

239

History

Before the misinformation train goes too far out of the station, there are a bunch of things you need to understand about PHP short tags.

The primary issue with PHP's short tags is that XML managed to choose a tag (<?) that was already used by PHP.

With the option enabled, you weren't able to raw output the xml declaration without getting syntax errors:

<?xml version="1.0" encoding="UTF-8" ?>

This is a big issue when you consider how common XML parsing and management is.

What about <?=?

Although <? causes conflicts with xml, <?= does not. Unfortunately, the options to toggle it on and off were tied to short_open_tag, which meant that to get the benefit of the short echo tag (<?=), you had to deal with the issues of the short open tag (<?). The issues associated with the short open tag were much greater than the benefits from the short echo tag, so you'll find a million and a half recommendations to turn short_open_tag off, which you should.

With PHP 5.4, however the short echo tag has been re-enabled separate from the short_open_tag option. I see this as a direct endorsement of the convenience of <?=, as there's nothing fundamentally wrong with it in and of itself.

The problem is that you can't guarantee that you'll have <?= if you're trying to write code that could work in a wider range of PHP versions.

ok, so now that that's all out of the way

Should you use <?=?

flowchart about whether or not to use the short echo tag

zzzzBov
  • 5,794
  • 1
  • 27
  • 28
  • 83
    I disagree with your snappy diagram. The correct answer is **99.99% YES** because most production environments are configured to use short tags. Supposing you blew it and they remove `=` in the future you can fix it in less than a minute, no matter how many thousands of files use it, you just do a project-wide search & replace of `=` for ` – dukeofgaming Jun 08 '12 at 00:07
  • 36
    @dukeofgaming, where are you getting your data about production environments being configured to use short tags? Disabling them is one of the most commonly suggested configurations that I've heard about, second only to disabling magic quotes. It also would make absolutely zero sense to have a dev environment that's different from production. – zzzzBov Jun 08 '12 at 00:11
  • 5
    Short tags were enabled by default until 5.3 http://www.php.net/manual/en/ini.core.php#ini.short-open-tag, most hosting services I know supported it with no problems and this was one of the reasons the Kohana framework used to encourage it. `=` will always be on (http://stackoverflow.com/a/6064813/156257) and most of the time they used to be on. You can prove me wrong by checking with your host if: they are disabled and using PHP < 5.3 *and* if they don't allow the setting to be overriden by users or upon special request; if all the previous is false, by all means worry about `=`. – dukeofgaming Jun 08 '12 at 01:30
  • 1
    @dukeofgaming, did you actually read my post? I personally support the use of `=` but due to the volatility of `` when mixed with XML, it's a common setting to override. It's an important distinction as to whether you're writing code for a library or personal use. If it's a library that needs to be backwards compatible, you simply wont be able to get away with short open tags. If you're just writing a template for your own drupal or wordpress blog, by all means, go ahead and use em. – zzzzBov Jun 08 '12 at 01:40
  • 3
    Yes, I did, and as I said, I just disagree with your snappy diagram. Particularly in the last part of the flow, because it won't disappear and there is no need to worry, in the drama-oriented PHP mailing list community this feature has no enemies whatsoever, and **tell you what, if it disappears I'll start a 200 Rep bounty for you to cash-in from this answer**. – dukeofgaming Jun 08 '12 at 17:35
  • 8
    You're not worried that `=` will be removed, and neither am I. Others might be, and if they are, they don't have to use `=`. Some people have irrational fear of using certain language features ([like leaving off closing tags in php](http://stackoverflow.com/questions/4410704/php-closing-tag/4453835#4453835)). – zzzzBov Jun 08 '12 at 18:11
  • 10
    That's precisely my point: *there is no need to worry*. I'd just put "Are you worried?" --yes--> "Go ahead and use them, there is no need to worry". It also feels like you are implying that leaving off closing tags is a bad practice, which is not. – dukeofgaming Jun 08 '12 at 19:14
  • 1
    Comments aren't the right place for this discussion, if you're interested in continuing, send me an email and I'll be glad to discuss this further. – zzzzBov Jun 08 '12 at 19:16
  • 3
    It is worth noting that *Since PHP 5.4.0, = is always available.* – Ronni Egeriis Persson Apr 02 '14 at 17:39
  • 1
    +1 for Before the misinformation train goes too far out of the station. Love it – Jon Mar 30 '15 at 14:49
  • -1 for not mentioning security implications. – ircmaxell Dec 03 '15 at 19:28
  • 4
    @ircmaxell mind sharing which security implications you're referring to so that I can fix this post? – zzzzBov Dec 03 '15 at 20:09
  • 4
    @ircmaxell, I happened to be referencing this answer again recently, and I noticed you still haven't clarified on your point about security implications. Is there a chance you could elaborate on your vague comment on security implications? – zzzzBov Mar 07 '17 at 16:14
  • @ircmaxell What are the security implications? – chris85 Jul 31 '17 at 14:34
  • 1
    Actually @zzzzBov, `````` is an XML processing instruction (PI) tag which is used *inside* XML documents. As such document is processed, when it reaches lines related to these instructions, a registered preprocessor subroutine should run and process the content of the PI tag, then replace it in, and move on. This is part of XML standard. And PHP specifically chose this tag to be compatible with this behaviour. That's why the language also is called "Hypertext Preprocessor". So overall, no, it should not be a huge problem to have ``` – Gelmir Feb 19 '18 at 12:38
  • And short-hand tag was introduced much later, which actually is in violation to XML specifications, since ```PIContent``` cannot contain ```?>``` string in it (considering the opening ```=``` actually wouldn't be valid as a PI opening tag). So that's it there. – Gelmir Feb 19 '18 at 12:44
  • 3
    As of today, on April 2018, this answer is no more valid. PHP development team shut down *completely* old short tags (they are no more activable through the `php.ini` config file or `ini_set()` function), but did not remove the short echo tag `= ... ?>`, which is now suggested, instead. Check here https://secure.php.net/manual/en/language.basic-syntax.phptags.php Furthermore, I underline that PHP is a **preprocessor**, used to generate XML documents too. It means that in the vast majority of cases, no PHP directive would be sent to a generic client with PHP tags still unparsed by the server. – yodabar Apr 03 '18 at 14:58
  • 2
    That flowchart could be massively simplified now - nobody should be using PHP < 5.4 anymore, and the short echo tag has remained since (it has even outlasted the short open tag option). There's no path other than "go ahead" now. – thomasrutter Dec 28 '18 at 12:16
  • @thomasrutter if you follow the flow chart it is as accurate today as it was 6 years ago. Just because most people get a "yes you should use `=`" result doesn't mean the logic has changed. – zzzzBov Dec 28 '18 at 12:40
  • 1
    I was not commentimg about its accuracy. – thomasrutter Dec 28 '18 at 14:11
32

Dusting off my PHP hat

I'd definitely favor the use of <?= $someVar ?> over the more verbose echo (simply personal preference). The only downside AFAIK is for users who are running pre-5.4.0, in which case short_open_tag must be enabled in php.ini.

Now having said that, if your project isn't OS, then it's a moot point. If it is, I'd either document the fact that short_open_tags must be enabled, or use the more portable of the two solutions.

Demian Brecht
  • 17,555
  • 1
  • 47
  • 81
  • 1
    Nitpick: Even though `=` is unaffected by `short_open_tag` on PHP 5.4, `` still is and if you get a habit of using short form tags, it's quite easy to forget what's supported on what version. – yannis Jun 05 '12 at 18:26
  • 10
    @YannisRizos It's good to distinguish `=` as "I'm outputting a variable now" for template-style usage, and ` – Izkata Jun 05 '12 at 19:31
  • 2
    +1 because Rasmus Lerdorf endorses the shorthand = tag. I watched one of his talks on the (then soon to be released) PHP 5.4. That is why since PHP 5.4.0 the = tag is always available. I have seen a lot of code pre PHP 5.4 that the = tag is used in the View of an MVC application but is used in the non-view files. – programmer Jun 05 '12 at 20:40
  • @Jason That's not what I'm saying. "Rasmus endorses foo" is _not_ an argument, "Rasmus endorses foo for this and that reason" however is. – yannis Jun 06 '12 at 15:00
  • 2
    @Yannis Rizos _"Rasmus endorses foo for this and that reason" however is._ Thanks for the tutelage, but my reasoning was since Rasmus Lerdorf endorses it, being the creator of the language and still having influence on PHP's development, changes were made to make the = tag always available. This is what I should have added to my original comment "Therefore the practice of using = in views will probably become even more widespread." Dang, I'll need to triple check my comments for now on...dots... – programmer Jun 06 '12 at 15:25
20

You should definitely try to avoid short form tags, whether it's <? or <?=.

The main technical reason is portability, you can never be sure that the short form tags will work for every given setup, as they can be turned off, lookup the short_open_tag directive. But you can always be absolutely certain that the long form will work everywhere.

It would save some typing and it would be better for code readability, IMO.

That's also a bad habit. I can't really tell you what you find more readable, but I'm feverishly against using code readability as an excuse to save yourself a couple of keystrokes. If you are concerned about readability, you should go for a template engine, this:

<input name="someVar" value="{someVar}">

is far more readable from both your examples.

Lastly, it's worth noting that short form tags are explicitly discouraged by major PHP projects, for example PEAR and Zend Framework.

yannis
  • 39,547
  • 40
  • 183
  • 216
  • +1 for inclusion of template engine usage. By far the best method (imho). – Demian Brecht Jun 05 '12 at 18:49
  • @DemianBrecht Well, it depends, for _some_ projects it might be an overkill. But in general yes, it's preferable. – yannis Jun 05 '12 at 18:50
  • Sure it's overkill, if it's a "hello, world" project ;) – Demian Brecht Jun 05 '12 at 18:53
  • 14
    +1 for templates. -1 for portability. Its a server side language. Challenges you need to focus on for a server are things like scalability and security. It would be an amazingly bad idea to invest serious time into making sure it would run on multiple platforms ... (just in case!) ... – riwalk Jun 05 '12 at 18:55
  • 3
    @Stargazer712 Hm? The only thing you need to do is use the standard ` – yannis Jun 05 '12 at 18:58
  • 13
    @Yannis: those few characters may not seem like much, but IMO they add up to a lot of noise. – kevin cline Jun 05 '12 at 19:24
  • @YannisRizos As noted by DemianBrecht in his answer, `=` is always on as of PHP 5.4 and can't be disabled. Your "new" server must be quite a downgrade if it isn't available, but was before. – Izkata Jun 05 '12 at 19:28
  • @kevincline Then go ahead and replace them completely, with a decent template engine. Heh, even a half decent one will do ;) If you are in full control of your server environment, and a few characters annoy you a lot, well, you might as well use short form tags, but that's doesn't really make them a good habit. – yannis Jun 05 '12 at 19:28
  • Besides which, PHP itself is a mixture of a templating language and a general-purpose language. `= $foo ?>` is meant to be the equivalent of `{ foo }`, but more flexible because you can also do `= funcCall() ?>` - not using it is silly if you're not using a pure template engine. – Izkata Jun 05 '12 at 19:29
  • @Izkata Did you read my comment to Demian's answer? `=` may be always on, but `` isn't, and since we're discussing habits, I'd say that if you make a habit of using the one, you'll probably use the other as well. And I'm sorry to put it bluntly, but crap like `= funcCall() ?>` will never make it into my code, just because the language supports it doesn't mean I have to use it, or that it's a good practice. Of course PHP can be used as a template language, I'm all too familiar with Rasmus' rant, but that doesn't really mean that it _should_ be used as such. – yannis Jun 05 '12 at 19:33
  • 9
    I think it should be mentioned that PHP's original purpose was to be _a template language_. Adding another template engine (more bloat) on top of PHP doesn't float my tuna boat. Just follow good practices (some good tips are here http://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html) when coding PHP mixed with HTML and you're good to go. – programmer Jun 05 '12 at 20:49
  • @YannisRizos, I never said that typing `` vs `=` would waste your time. I said that worrying about portability would waste your time. The latter takes significant time out of the day. – riwalk Jun 05 '12 at 20:51
  • @Jason No it should be mentioned, it's absolutely irrelevant. Original purpose was in 1995, and if I'm not horribly mistaken that was a while ago. Should I only do text processing in Perl, because that was its original purpose? And LISP wasn't even supposed to be a programming language. – yannis Jun 06 '12 at 03:22
  • 2
    @Yannis Rizos Yes it should be mentioned because people new to PHP might think they are obligated to use [whizbang] template engine in their PHP projects without considering using pure PHP instead. _Should I only do text processing in Perl_, maybe not but I figure that by now Perl is pretty darn good at text processing - likewise with PHP and templating. – programmer Jun 06 '12 at 15:14
  • 1
    I don't see this as a very convincing answer for outright saying that you should avoid short tags. Portability is indeed a possible short fall, but how often are you really concerned with portability in a server environment (where you should have full control and often the application will never be distributed to others)? You mention the readability thing, but it doesn't seem like a good argument at all. There's nothing wrong with saving keystrokes if it's also more readable (and I think it is). And those conventions seem solely focused on portability. – Kat Feb 18 '16 at 14:07
  • What do you call {{someVar}} ?? trying to learn it but don't know what it's named – TheCrazyProfessor Sep 09 '17 at 16:39
  • @Kat, "I don't see this as a very convincing answer", well, it really isn't any more. :) It should be updated or something, as it became obsolete long ago: the truth is "nowadays" (well, since 5.4, which was released *earlier* than this anwer, actually :) ) the opposite. As e.g. Hexodus quoted the PHP docs [in his answer](https://softwareengineering.stackexchange.com/a/311257/122429): "The tag `=` is always available regardless of the `short_open_tag` ini setting." So, it's definitely safe, portable, practical, useful etc. etc., and recommended to use. – Sz. May 29 '20 at 20:22
  • @yannis I get personal preference, but you could've at least updated your post to mention that your points no longer hold any water. New users should not be mislead just because you have a negative opinion. – Chazy Chaz Mar 27 '21 at 14:50
20

The PHP-Documentation clearly says that you can use short echo tags safely:

5.4.0 The tag <?= is always available regardless of the short_open_tag ini setting.

Although this is for PHP version 5.4 and greater but everybody should at least use this one. I would prefer them for templating purposes only.

Hexodus
  • 301
  • 2
  • 4
11

Reasons for using short tags:

  • They are shorter.

Reasons for not using short tags:

  • They introduce one more configuration gotcha - while you do control the server most of the time in a professional context, if you plan to release your code to the general public, short tags may break unrepairably for people who use it on, say, shared hosting.
  • They make it way too easy to casually drop un-sanitized strings into your output. This is scary because it may introduce XSS vulnerabilities. While long tags do nothing directly to prevent this, they do signal to the programmer that maybe what they are doing isn't the right thing, and they should start using a template system that automatically handles HTML-encoding for them right now. Outputting dynamic strings with long tags is painful, which is a good (educative) thing.
tdammers
  • 52,406
  • 14
  • 106
  • 154
  • That's the answer to accept IMO, even tho templates won't make everything XSS safe (user data in a script's src attribute will always be unsafe) and I don't know if template mechanism are aware of the proper echoing context; what if the PHP variable ends up in a script tag content? In a SVG embeded in the HTML? – Xenos Mar 23 '19 at 12:53
  • @Xenos clearly that depends on the template system in question, and there is no silver bullet; but most of them do reduce the bug surface, and the number of scenarios where manual diligence (the single most important source of security bugs) is required. "Don't put dynamic content in script tags" is easier to follow (and audit for) than "make sure all dynamic content is HTML-encoded properly everywhere". – tdammers Apr 04 '19 at 08:28
  • So your second (not to) point is akin to: "reasons not to use knifes: you can cut yourself?". Because the first one stopped being valid 2 years after you posted this. – Chazy Chaz Mar 27 '21 at 15:01
9

As of PHP 7.4, the playing field changes a bit:

<? ?> is officially deprecated and will be removed in PHP 8.0.

PHP RFC: Deprecate PHP Short open tags explicitly states that <?= ?> is unaffected. This would indicate (according to me, not the RFC) that its usage is not discouraged.

Etienne Bruines
  • 201
  • 2
  • 4
6

I think that the <?= version is a good/acceptable practice, provided that you only use it for final output of variables and avoid any function-calls or ternary-logic that aren't directly related to the presentation of the data.

It's certainly much better than <? echo($x); ?> everywhere.

Long-term, you may want to look into templating engines such as Smarty.

Darien
  • 3,453
  • 2
  • 19
  • 18
  • 3
    Smarty was once _the_ template engine, but right now it's an outdated & bloated mess, and you should really steer clear. – yannis Jun 05 '12 at 18:51
-3

To be honest, I think that echoing a result whichever the method is (old or new fashion) is something pretty obsolete while MVC celebrates 33 years already.

I would say that yes, this is a good practice to encapsulate the incoming server (php) data within an XML document and process it in your applicative/client layer, thus, saving you even the idea of using such a tag.

sebas
  • 11
  • 1