PHP switch case $_GET's variables and switch c

2019-05-15 16:09发布

Say I have an URL like www.mysite.com/index.php?login=0. Is it possible to switch case $_GET's variables and switch case $_GET's variable's values?

Something like:

switch ($_GET) {
    case 'login' :
        switch($_GET['login']) {
            case '0' :
                echo 'Login failed!';
                break;
            case '1' :
                echo 'Login successful.';
                break;
        }
        break;
    case 'register' :
        switch ($_GET['register']) {
            case '0' :
                echo 'Registration failed!';
                break;
            case '1' :
                echo 'Thank you for registering.';
                break;
        }
        break;
    default :
        echo 'Some other message';
        break;
}

I'm not sure if switch case can be used on associative arrays. What am I doing wrong? Cheers!

3条回答
Summer. ? 凉城
2楼-- · 2019-05-15 16:37

Just Use this:

switch($_GET['key']) //it will return you value of particular parameter.
case 'value1':
//write your statement here.
break;
case 'value2':
//write your statement here.
break;
//and so on
查看更多
成全新的幸福
3楼-- · 2019-05-15 16:48

I do not think it will work like this, $_get will return an array and these comparisons will not work. Switch statements need to evaluate to a constant.

查看更多
仙女界的扛把子
4楼-- · 2019-05-15 16:55

You have to enclose the switch in a foreach() loop.

foreach ($_GET as $key => $value) {
    switch ($key) {
        case 'login' :
            switch ($value) {
                case '0' :
                    echo 'Login failed!';
                    break;
                case '1' :
                    echo 'Login successful.';
                    break;
            }
            break;
        case 'register' :
            switch ($value) {
                case '0' :
                    echo 'Registration failed!';
                    break;
                case '1' :
                    echo 'Thank you for registering.';
                    break;
            }
            break;
        default :
            echo 'Some other message';
            break;
    }
}
查看更多
登录 后发表回答