php - PHP - 多个(很多)if(isset)检查 - 有没有捷径
问题描述
我有一个包含大量 $_GET 参数的页面,但并不总是保证所有这些参数都可以使用。所以我现在收到很多关于未定义变量的警告。我显然需要检查它是否用 isset 设置,所以我避免警告,但我确实有 80 !
例如,仅显示很少(但它们远不止这些,可能是 80 个)
$pt2r2c1 = htmlspecialchars($_GET['pt2r2c1']);
$pt2r2c2 = htmlspecialchars($_GET['pt2r2c2']);
$pt2r2c3 = htmlspecialchars($_GET['pt2r2c3']);
$pt2r3c1 = htmlspecialchars($_GET['pt2r3c1']);
$pt2r3c2 = htmlspecialchars($_GET['pt2r3c2']);
$pt2r3c3 = htmlspecialchars($_GET['pt2r3c3']);
$pt2r4c1 = htmlspecialchars($_GET['pt2r4c1']);
$pt2r4c2 = htmlspecialchars($_GET['pt2r4c2']);
$pt2r4c3 = htmlspecialchars($_GET['pt2r4c3']);
$pt2r5c1 = htmlspecialchars($_GET['pt2r5c1']);
$pt2r5c2 = htmlspecialchars($_GET['pt2r5c2']);
所以我开始手动执行此操作……但在 40 岁时我觉得自己很愚蠢,我想是否有更好的方法来做到这一点。
if (isset($_GET['pt1r5c3'])) {
$pt1r5c3 = htmlspecialchars($_GET['pt1r5c3']);
}
if (isset($_GET['pt1r6c1'])) {
$pt1r6c1 = htmlspecialchars($_GET['pt1r6c1']);
}
if (isset($_GET['pt1r6c2'])) {
$pt1r6c2 = htmlspecialchars($_GET['pt1r6c2']);
}
if (isset($_GET['pt1r6c3'])) {
$pt1r6c3 = htmlspecialchars($_GET['pt1r6c3']);
}
if (isset($_GET['pt2r1c1'])) {
$pt2r1c1 = htmlspecialchars($_GET['pt2r1c1']);
}
if (isset($_GET['pt2r1c2'])) {
$pt2r1c2 = htmlspecialchars($_GET['pt2r1c2']);
}
if (isset($_GET['pt2r1c3'])) {
$pt2r1c3 = htmlspecialchars($_GET['pt2r1c3']);
}
解决方案
好的,感谢评论中的一些提示,我意识到我可以尝试使用简单的数组和 foreach。因此,经过反复试验,我设法做到了。希望对其他人有所帮助。
$tree_variables_array = ['pt1r1c1', 'pt1r1c2', 'pt1r1c3', 'pt1r2c1'];
foreach ($tree_variables_array as $var) {
if(isset($_GET[$var])) {
$$var = htmlspecialchars($_GET[$var]);
}
}
推荐阅读
- angular - 为什么角材料中的对话表现不一致?
- php - 使用 AJAX 进行 jquery 验证后的图像上传
- node.js - Sequelize 作为 express JS 中的函数总是返回 isFulfilled 和 isRejected false
- python - 使用警告上下文管理器特别沉默的 Pandas SettingWithCopyWarning?
- python - 带有运算符的 if 语句中的语法错误
- git - Git rebase:通过运行命令修复
- mysql - mysql 将字符串转换为日期时间格式
- mysql - 如何获取不在表“service_gos”中的“ids”(Laravel)
- c# - 从委托访问范围变量
- java - 如何使用动态捆绑安装在 Equinox 中运行子进程?