PHP:Switch()如果{}其他控制结构

Chr*_*ris -2 php logic if-statement switch-statement

如何在不使用Switch或If的情况下执行逻辑?

比如check_id_switch($ id)

function check_id_switch($id){
    switch($id){
        case '1': 
        $HW = 'Hello, World!';
        break;
        default:
        $HW = 'Goodbye, World!';
        break;
     } 
  return $HW;
 }
Run Code Online (Sandbox Code Playgroud)

或者实例check_id_if($ id)

function check_id_if($id){
    if($id == 1){
     $HW = 'Hello, World!';
    }
   else{ 
   $HW = 'Goodbye, World!';
 }
return $HW;
}
Run Code Online (Sandbox Code Playgroud)

check_id_switch($ id)和check_id_if($ id)这两个函数都将检查ID的引用.

如何在不使用php中的if/switch语句的情况下创建与上面相同的逻辑?我也想避免使用forloops.

关于开关/ if的性能有多个争论,但是如果有另一个控制结构,它是在下面还是外面执行上述控制结构?

添加登录脚本作为if语句的示例.我删除了登录脚本的主干.如果为true,则无需查看已完成的操作:false.我觉得下面是笨重而且不洁净的.

if(!empty($_POST))
{
    $errors = array();
    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);
    $remember_choice = trim($_POST["remember_me"]);

    if($username == "")
    {
        $errors[] = ""; 
    }
    if($password == "")
    {

        $errors[] = "";
    }

    if(count($errors) == 0)
    {
        if(!usernameExists($username))
        {
            $errors[] = "";
        }
        else
        {
            $userdetails = fetchUserDetails($username);

            if($userdetails["active"]==0)
            {
                $errors[] = "";
            }
            else
            {
                $entered_pass = generateHash($password,$userdetails["password"]);

                if($entered_pass != $userdetails["password"])
                {
                    $errors[] = "";
                }
                else
                {

                    // LOG USER IN
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Nar*_*dia 7

您可以使用ternary运算符

function check_id_switch($id){
    return $HW = ($id == 1) ? 'Hello, World!' : 'Goodbye, World!';
}
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地使用Rizier的评论作为评论

function check_id_switch($id = '2'){
    $arr = [1 => "Hello, World!", 2 => "Goodbye, World!"];
    return $arr[$id];
}
Run Code Online (Sandbox Code Playgroud)