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
https://forums.phpfreaks.com/topic/215831-proper-use-of-multiple-if-statements/
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.

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.