PHP-如果(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]);
}
}

相关内容

最新更新