Php 将$U GET变量始终保持为";ac";或;ar";价值观

Php 将$U GET变量始终保持为";ac";或;ar";价值观,php,Php,我想在任何情况下保持$\u 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');} 如何在一行中写出第一行和第三行?

我想在任何情况下保持
$\u 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');}
如何在一行中写出第一行和第三行?

或者其他更短的解决方案

尽管这会使其难以读取,但您可以在
if
语句中进行赋值,如果未设置
$\u GET['st']
,则使用三元运算符设置无效值:

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

请注意,如果您使用的是PHP7+,您可以使用空合并运算符
??
,以避免在
$\u GET['st']
未设置时出现通知级错误:

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

正如@mickmackusa指出的,可以使用数组中的
进一步简化代码:

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

如果你在我对尼克发表评论的同时投了反对票,那纯粹是巧合。我不会对包括努力证明在内的问题投反对票。(也就是说,我不认为这个问题显示出极大的努力或值得一次中立的投票。)在_array()
中使用
,它会更短、更容易扩展。