代码之家  ›  专栏  ›  技术社区  ›  qadenza

将$GET变量始终保持为“ac”或“ar”值

php
  •  -1
  • qadenza  · 技术社区  · 5 年前

    我想保留 $_GET['st'] $status 成为 ac ar 在任何情况下,例如,如果用户更改了地址栏中的内容。

    if(!isset($_GET['st'])){header('Location: notes.php?st=ac');}  
    else{$status = $_GET['st'];}  
    if(!($status == 'ac' || $status == 'ar')){header('Location: notes.php?st=ac');}
    

    如何在一行中写出第一行和第三行?
    或者其他更简短的解决方案?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Nick SamSmith1986    5 年前

    尽管这使你很难阅读,但你可以在 if 语句,使用三元运算符设置无效值 $_GET['st'] 未设置:

    if (($status = $_GET['st'] ?: '') != 'ac' && $status != 'ar') { header('Location: notes.php?st=ac'); }  
    

    Demo on 3v4l.org

    注意,如果使用php7+,则可以使用空合并运算符 ?? 为了避免通知级别错误,如果 $GET [ ST ] 未设置:

    if (($status = $_GET['st'] ?? '') != 'ac' && $status != 'ar') { header('Location: notes.php?st=ac'); }  
    

    Demo on 3v4l.org

    正如@mickmackusa所指出的,可以使用 in_array :

    if (!in_array($status = $_GET['st'] ?? '', ['ac', 'ar'])) { header('Location: notes.php?st=ac'); }  
    

    Demo on 3v4l.org

    推荐文章