php - 将 $_GET 变量始终保留为“ac”或“ar”值
问题描述
我想在任何情况下都保持$_GET['st']
ie$status
为ac
OR 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
,则使用三元运算符设置无效值:$_GET['st']
if (($status = $_GET['st'] ?: '') != 'ac' && $status != 'ar') { header('Location: notes.php?st=ac'); }
请注意,如果您使用的是 PHP7+,则可以使用 null 合并运算符??
来避免未设置的通知级别错误$_GET['st']
:
if (($status = $_GET['st'] ?? '') != 'ac' && $status != 'ar') { header('Location: notes.php?st=ac'); }
正如@mickmackusa 指出的那样,可以使用以下代码进一步简化代码in_array
:
if (!in_array($status = $_GET['st'] ?? '', ['ac', 'ar'])) { header('Location: notes.php?st=ac'); }
推荐阅读
- sitefinity - sitefinity ActionResult 缺少查询字符串
- xml - XSLT:如何调用以字符串形式给出的用户定义函数
- python - 如何在 Jupyter 笔记本中使用 Pandas 永久更改数据框样式?
- python - 具有多个键的 Python 字典列表
- sql - 在 SQL Server 中选择以显示表 OnHand、Sale 和 Purchase 中的所有不同行,其中一个/或 Qty 字段不为空
- c++ - ffmpeg/Libavcodec 找不到编解码器
- vscode-extensions - vscode文件资源管理器复制/粘贴如何工作?
- javascript - DataTables 警告:表 id={id} - 请求行 {row-index}、列 {column-index} 的未知参数“{parameter}”
- java - 我需要一个循环来向用户询问 5 次 1 到 10 之间的数字
- java - 如何在 ListIterator(反向)迭代期间正确添加对象?