Reputation: 5087
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.
Upvotes: 0
Views: 277
Reputation: 321618
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;
Upvotes: 7
Reputation: 5369
Make a Karnaugh map. Don't avoid "switch" when it actually makes sense.
Upvotes: 0
Reputation: 2218
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; }
Upvotes: 2
Reputation: 655229
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;
}
Upvotes: 5