For example, take the if control construct.


There is such a use case:

 <?php if ( $a ) : ?> Блаблабла <?php endif; ?> 

And there is this:

 <?php if ( $a ) { ?> Блаблабла <?php } ?> 

Fiddle: sandbox.onlinephpfunctions.com .


Are there any differences between them?

  • one
    No, absolutely not. But the first option is used for templating and only in it. And the <?php tag is not necessary to write, you can simply <? , then the sample code is even shorter: <? if ($a) : ?> .... <? endif; ?> <? if ($a) : ?> .... <? endif; ?> <? if ($a) : ?> .... <? endif; ?> - Vasily Barbashev
  • 2
    @ Vasily Barbashev Is it possible to write abbreviated <? specified in php.ini (parameter short_open_tag) and in recent versions of php, the abbreviated entry is disabled by default. - Mike

2 answers 2

The difference is only in syntax, the behavior and logic used is fully equivalent. Read that form

 if ( $a ) : 

more convenient for shifting PHP and HTML codes: it's easier to navigate where a particular block is closed. However, this bias is not particularly welcomed by the community, so this form is practically not used. In most cases, preference is given to the form

 if ( $a ) { 
  • And to me here some time ago on the SO community said that the first form was more welcome lately and recommended in the code examples on SO to stick with it :) - Mike
  • @Mike in the templates? Maybe. To be honest, I prefer templates without angle brackets, such as <% or <? Php. Perhaps in the templates of this type, the first option would look more appropriate. - cheops
  • Recommended everywhere. although I like the second form more clearly. comes from the time of C and in many languages ​​is present and intuitive - Mike
  • one
    To be honestly surprised, since I also always prefer the C-form. Yes, PSR standards do not mention the first form of mine at all, and this is a serious indicator. - cheops
  • I study Yii2 and everywhere I use ( in templates ) the use of the first option (for example, there are a few in the documentation) and I use it myself. And now I watched the video and there the author uses the second option - therefore I became interested in this moment. But the first option really allows ... easier to navigate where one or another block is closed. ... - Roman Grinyov

Ternary operator:

Pros:

  • Less code

Minuses:

  • runs longer (noticeable with a large load and large loop iterations)
  • understanding is compiled a little (with large nesting levels)
  • you can not leave if without else ie

if it was

 if ($a === $b) { echo "111"; } else { echo "222"; } echo ($a === $b) ? "333" : "444"; 

and then you need to remove the else

 if ($a === $b) { echo "111"; } echo ($a === $b) ? "333"; //ошибка так сделать нельзя нужно переписывать на if