首页 > 解决方案 > 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']);
}

标签: phpisset

解决方案


好的,感谢评论中的一些提示,我意识到我可以尝试使用简单的数组和 foreach。因此,经过反复试验,我设法做到了。希望对其他人有所帮助。

   $tree_variables_array = ['pt1r1c1', 'pt1r1c2', 'pt1r1c3', 'pt1r2c1'];
        
        
    foreach ($tree_variables_array as $var) {
      if(isset($_GET[$var])) {
        $$var = htmlspecialchars($_GET[$var]);
      }
    }

推荐阅读