簡體   English   中英

PHP - 如果(isset)檢查多個(很多) - 有沒有捷徑

[英]PHP - Multiple (a lot) if (isset) checks - Is there a short way

我有一個包含大量 $_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]);
      }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM