转换If / Else切换[重复]

This question already has an answer here:

How do I convert the below to a switch instead of If/Else? I read that if I have more than if/elseif/else that i should use a switch instead

 $domain = ($_SERVER['HTTP_HOST']);

    if ($_SERVER['HTTP_HOST']=="domain1.com" && strpos($_SERVER['REQUEST_URI'], 'ab03') !== false ) {
        codeblock();
        $tlink = "http://google.com";
    } elseif ($_SERVER['HTTP_HOST']=="domain1.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
        $tlink = "http://cnn.com";
} elseif ($_SERVER['HTTP_HOST']=="domain2.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
        $tlink = "http://yahoo.com";
} elseif ($_SERVER['HTTP_HOST']=="domain3.com" && strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
        $tlink = "http://example.com";
    } else {
        $tlink = "http://cbs.com";
    }
</div>

You could have found this yourself in a 5 sec Google search...

switch($i){
   case 0:
   break;
}

Simply replace $i with $_SERVER['HTTP_HOST'] to compare and 0 with the wanted value example domain1.com.

http://php.net/manual/en/control-structures.switch.php

However the switch is not really adapted to your code as you have multiple conditions in your if. Since the second condition seems to be always the same, you could simply put the switch in the if of the second condition or use the clause inside each case but this would be redundant code.

try use code

    switch ($domain) {
    case 'domain1.com':
        if(strpos($_SERVER['REQUEST_URI'], 'ab03') !== false) {
            codeblock();
            $tlink = "http://google.com";         
        } elseif(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
            $tlink = "http://cnn.com";
        }
    break;
    case 'domain2.com':
        if(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false) {
            $tlink = "http://yahoo.com";
        }
    break;
    case 'domain3':
        if(strpos($_SERVER['REQUEST_URI'], 'ab05') !== false ) {
            $tlink = "http://example.com";
        }
    break;
    default:
        $tlink = "http://cbs.com";
    break;  
}