Jump to content

Proper use of multiple IF statements?


mfleming

Recommended Posts

Hi.

 

Currently I have code the uses both TRUE. IF statements and FALSE statements to move on. 

 

For example.

 

Is it better to use:

 

Where B=A
C=A

IF A=B {
IF C=B{
ECHO 'HELLO WORLD';

}ELSE
ECHO 'C DOES NOT EQUAL B';

}ELSE
ECHO 'A DOES NOT EQUAL B'; '

 

 

OR is it better to do it like this:

 

 

Where B=A
C=A

IF A<>B {
ECHO 'C DOES NOT EQUAL B';

ELSE

IF C<>B{
ECHO 'C DOES NOT EQUAL B';

ELSE

ECHO 'HELLO WORLD';
'[/code

Link to comment
Share on other sites

There is no best approach in these matters.  I try and think about maintainability and use code that most clearly represents the logic of the application.  With php there is one concept that comes up, and that is variable type.  Because PHP will typecast variables on the fly, people rarely think about this, but there are times when you make your code more robust by checking not only the boolean value of a variable, but also it's type.  So for example, there are cases where instead of using:

 

 

$retval = somefunction();

if ($retval == false) {
  // error
} else {
// good
}

 

Your code will be more reliable if you have instead:

 

$retval = somefunction();

if ($retval === false) {
  // error
} else {
// good
}

 

In the first case if the function returns 0, it will evaluate to false and the error section will be triggerd.  This might not be what you want to happen, as zero might in this context be a valid retval.  If you only want to enter the error section if the function explicitly did a "return false;"  then you want to use the "===".

 

I also try and use switch() {} blocks as much as possible rather than long if then else blocks.

Link to comment
Share on other sites

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.