TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Nested if's or is there a better way? (http://www.talkphp.com/absolute-beginners/3954-nested-ifs-there-better-way.html)

xtsu 02-09-2009 08:31 PM

Nested if's or is there a better way?
 
Hey Guys and Gals,

I know when I have written something for PHP there is a million ways to do the same thing. My question is what is the best way with if's and elseif's?

What I want to do is I have 4 variables to compare. If variable 1 is less than 30 then do this that is fairly simple. However, the issue becomes harder when I have to compare all 4 variables at once. Var1 could be equal to 8- but var 2, 3 and 4 are all less than 400 so do this. or 2 and 4 could be greater than 400 but 3 less than, then do this.

The way I do it now is this

Code:

if($row[2]>='80' && $data[1]<'300' && $data[4]>='400' && $data[6]>=400)
I know that I could also do it another way like this:

Code:

if($row[2]>='80'){
    if ($data[1]<'300') {
          if ($data[4]>='400') {
              if ($data[6]>=400){
              }
          }
      }
}

I am just not sure which would be easier, as well there might be a different way to do this. The first way seems to be too specific and I might miss some cases. The second way would be 100% sure not to miss any cases but seems to be way more coding than I need as well not the right way to do it.

Suggestions?

Sakakuchi 02-09-2009 09:00 PM

I'd definetely prefer the first one, because the code is easier to understand, simpler - and looks just nicer.

xtsu 02-09-2009 10:30 PM

I do as well, I just don't want to miss any cases.

Wildhoney 02-09-2009 10:57 PM

Yes. The first way, I suppose. Although lay it out a little better by adding more spaces:

php Code:
if ($row[2] >= 8 && $data[1] < 300 && $data[4] >= 400 && $data[6] >= 400)
{
    /* Do something... */
}


All times are GMT. The time now is 01:50 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0