Jump to content

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


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
 }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.