如何在不使用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;
}
或实例check_id_if($id)
function check_id_if($id){
if($id == 1){
$HW = 'Hello, World!';
}
else{
$HW = 'Goodbye, World!';
}
return $HW;
}
这两个函数check_id_switch($id)和check_id_if($id)将检查id到它的引用。
如何在php中不使用if/switch语句创建与上面相同的逻辑?我还希望避免使用for循环。
关于switch/if的性能存在多种争论,但如果存在另一种控制结构,它是否低于或优于上述控制结构?
添加Login Script作为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
}
}
}
}
}
您可以使用与
相同的ternary
运算符function check_id_switch($id){
return $HW = ($id == 1) ? 'Hello, World!' : 'Goodbye, World!';
}
或者你可以简单地使用Rizier的答案,他评论为
function check_id_switch($id = '2'){
$arr = [1 => "Hello, World!", 2 => "Goodbye, World!"];
return $arr[$id];
}