Jump to content

if(){} or if(): endif;


Obi1-Cannabis

Recommended Posts

Hi,just for curiosity, i've allways used the syntax

if(this == that){    //do something}else{   //do something else }

But i'd like to know if it's a better practice to use

if(this == that):   //do somethingelse:  //do something elseendif;

if yes, why?

Link to comment
Share on other sites

The braces are canonical, i.e. best practice, mostly from a legibility point of view. It's way easier to see the structure if you use them.

Link to comment
Share on other sites

I don't think there's much of a performance difference, but the alternative syntax can be useful if you're doing things like writing out a bunch of HTML on a page.

<?php if(this == that): ?>html herehtml herehtml herehtml herehtml herehtml here<?php else: ?>html herehtml herehtml herehtml herehtml herehtml herehtml here<?php endif; ?>

That may look cleaner to you than this:

<?php if(this == that) { ?>html herehtml herehtml herehtml herehtml herehtml here<?php } else { ?>html herehtml herehtml herehtml herehtml herehtml herehtml here<?php } ?>

Link to comment
Share on other sites

I think the key words in jsg's reply are "to you." This is really a matter of personal preference (or in-house style if you're corporate). I never worked with the alternative style in any C-type language before I came to PHP, so it does not look cleaner to me. I can see a seasoned VB programmer liking it, however.

Link to comment
Share on other sites

Guest FirefoxRocks

This is the fastest:

<?phpif($blah === 'that') {// ...}else {// ...}?>

You can also use switch statements:

<?phpswitch($blah) {	case 'that':		// ...		break;	default:		// ...		break;}?>

I would recommend the use of curly brackets as it makes it easier to read your code, and if you write more than one line of code, it works. Also, strict comparisons (using ===) are faster than value, or whatever they're called, comparisons (using ==).

Link to comment
Share on other sites

If you don't use braces you can only use one line.Ok-

if(//true)	 //Do somethingelse	 //Do something else

Not ok-

if(//true)	 //Do something	 //Am I in the true statement? No.else	 //Do something else	 //Am I in the else statement? No.

Link to comment
Share on other sites

If you don't use braces you can only use one line.Ok-
if(//true)	 //Do somethingelse	 //Do something else

Not ok-

if(//true)	 //Do something	 //Am I in the true statement? No.else	 //Do something else	 //Am I in the else statement? No.

By putting a colon after the if() you can add several lines. It's a syntax from BASIC-derived languages
if(condition):  // Several  // lineselse:  // of  // codeendif;

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...