首页 > 解决方案 > 将 $_GET 变量始终保留为“ac”或“ar”值

问题描述

我想在任何情况下都保持$_GET['st']ie$statusacOR 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');}

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

标签: php

解决方案


虽然它很难阅读,但您可以在语句中进行赋值,如果未设置if,则使用三元运算符设置无效值:$_GET['st']

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

3v4l.org 上的演示

请注意,如果您使用的是 PHP7+,则可以使用 null 合并运算符??来避免未设置的通知级别错误$_GET['st']

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

3v4l.org 上的演示

正如@mickmackusa 指出的那样,可以使用以下代码进一步简化代码in_array

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

3v4l.org 上的演示


推荐阅读