views:

164

answers:

4

Is there anyway I can clean up

if($class == 2 AND $posts >=1){$showpost ="1";} else {$showpost ="$posts";
if($class == 3 AND $posts >=2){$showpost ="2";} else {$showpost ="$posts";
if($class == 4 AND $posts >=3){$showpost ="3";} else {$showpost ="$posts";
if($class == 5 AND $posts >=4){$showpost ="4";} else {$showpost ="$posts";
if($class == 6 AND $posts >=5){$showpost ="5";} else {$showpost ="$posts";
if($class == 7 AND $posts >=6){$showpost ="6";} else {$showpost ="$posts";
}}}}}}

As I don't want }}}}}} at the end.

+5  A: 

You can strip all $showpost ="$posts"; statements except for the last:

if ($class == 2 AND $posts >=1) {
    $showpost = "1";
} else if ($class == 3 AND $posts >=2) {
    $showpost = "2";
} else if ($class == 4 AND $posts >=3) {
    $showpost = "3";
} else if ($class == 5 AND $posts >=4) {
    $showpost = "4";
} else if ($class == 6 AND $posts >=5) {
    $showpost = "5";
} else if ($class == 7 AND $posts >=6) {
    $showpost = "6";
} else {
    $showpost ="$posts";
}

Or even summarize it to this:

if ($class >= 2 && $class <= 7 && $posts >= ($class - 1)) {
    $showposts = $class - 1;
} else {
    $showposts = $posts;
}
Gumbo
you can also remove unnecessary quotes as in $showpost = "$posts"; and $showpost = "1";
Salman A
Thanks for the summarized version.
Homework
+2  A: 

You can use this, not nice but will work.

if($posts >= ($class - 1) AND $class >= 2 AND $class < 8) { $showpost = $class - 1; }
else { $showpost = $posts; }
martin.malek
The variables end up as strings in the example code, so you need strval to make it similar.
OIS
@joey: $post have to be equal or larger then ($class - 1) in every if sentence in example. $class have to be larger then 1 and less then 8. Just put those 3 requirements together and you got the code by martin.
OIS
Thanks, it's not a nice looking, but it works!
Homework
+7  A: 
if (($class >= 2) && ($class <= 7) && ($posts >= $class - 1))
    $showpost = $class - 1;
else
    $showpost = $posts;

The if is split into two sections:

 if (
     ($class >= 2) && ($class <= 7) // Check $class is between 2 and 7 inclusive

     && ($posts >= $class - 1)) // Check $posts >= $class -1
                                // so if $class is 4 this checks if $posts >= 3

This matches the logic in your original code - it's just a matter of seeing the pattern.

If you need $showpost to be a string (chances are you don't), you can cast to string like this:

$showpost = (string)$showpost;
Greg
This solution worked, but could you explain this, as it makes no sense to me.
Homework
`($class >= 2) ` - does that the applicable if-statement body would have done. `$showpost = $posts;` - does what would have happened if none of the if statements were true.
Amber
Thanks indeed. That helps out a lot.
Homework
A: 

Make a Karnaugh map. Don't avoid "switch" when it actually makes sense.

artificialidiot