简体   繁体   中英

Cleaning up PHP

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.

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;

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;
}

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; }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM