Jump to content

Is either if statement "neater" or more legible than the other?


MySQL_Narb

Recommended Posts


//do some validation on the url
if($url == 'http://www.youtube.comhttp://www.youtube.com'):
   $url == 'http://www.youtube.com';
elseif(preg_match('~youtube.com\/\/(.+?)~', $url)):
   $url = preg_replace('~.com\/\/~', '.com/', $url);
endif;

 

VS.

 


//do some validation on the url
if($url == 'http://www.youtube.comhttp://www.youtube.com'){
   $url == 'http://www.youtube.com';
}elseif(preg_match('~youtube.com\/\/(.+?)~', $url)){
   $url = preg_replace('~.com\/\/~', '.com/', $url);
   echo $url;
}

 

The second one is usually what I do, but it always gives me a bad feeling just leaving the "elseif" there as if there's always suppose to be an "else" to end a elseif statement.

 

Not sure why I have this feeling. :/

It's just personal preference mostly, however using curly-braces is more common than the alternative (colon/endif) syntax in PHP files. 

 

I personally find the alternative syntax to be more legible within template files where your mixing PHP and HTML.  Such as:

<p>Some HTML or something</p>
<?php if ($blah): ?>
  <div>Some conditional HTML</div>
<?php endif; ?>

 

@kicken I agree with you on that one, and it seems to be used most in WordPress themes I've noticed

 

There are a few ways we can declare if and else statements which hasn't already been mentioned:

 

//horrible way which turns my stomach to see
if( $foo )
 echo $bar;
else
 echo $fooBar
//shorthand version which is nice to use in methods
class User {
 isLoggedIn(){
   return ( $this->loggedIn ) ? true : false;
   //obviously we could just return the property but just illustrating the point
 }
}

Archived

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

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.