首页 文章

如何在PHP中检查2个关键字

提问于
浏览
-2

我想查看我的会话 . 以下代码有效:

if ($_SESSION["rol"] != 'trainer') {
}

但是这段代码不起作用:

if ($_SESSION["rol"] != 'trainer' || 'commandant') {
}

它应该检查两者,因为两者都有权限 . 我究竟做错了什么?

3 回答

  • 1

    用这个

    if ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] != 'commandant') {
    
    }
    
  • 1

    我可能会执行以下操作,其中 isset 确保密钥存在(并且当密钥不可用时帮助减少警告):

    if (isset($_SESSION["rol"]) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] == 'commandant')) {
        echo 'do some...';
    }
    

    array_key_exists 是使用 isset 检查密钥的不错选择:

    if (array_key_exists('rol', $_SESSION) && ($_SESSION["rol"] != 'trainer' || $_SESSION["rol"] == 
    'commandant')) {
        echo 'do more...';
    }
    

    希望有所帮助 .

    PS:带有 in_array() 的@dexter解决方案随着时间的推移会更好,更容易维护 .

  • 1
    $role = ['trainer','commandant'];
    
    if(!in_array($_SESSION['rol'],$role))
    {
     //do some stuff
    }
    

相关问题