2009-08-07 34 views
8

我剛啓用錯誤報告和哇多麼令人震驚的我大概幾千甚至幾百個啓事是這樣如何擺脫數百個PHP未定義索引通知?

Notice: Undefined index: action in C:\webserver\htdocs\header.inc.php on line 18 

據我所知,他們是因爲我打電話withoutsetting它或任何一個變量,但有更簡單例如,如果頁面中有50個變量正在報告這個問題,有沒有更簡單的方法來正確編碼該頁面以修復它們?

而且我並不想只是隱藏起來,我認爲這將是最好的解決這些問題

這裏是我行公佈第一

if ($_GET['p'] == "account.edit.topfriends" || $_GET['action'] == "newmember" || $_GET['p'] == "account.profile.name") { 
    //some more code here 
} 

回答

13

我通常喜歡用ternary語句在我的腳本的頂部初始化值。


$_GET['p'] = (isset($_GET['p']) ? $_GET['p'] : 'default'); 

當然,你可能會使用一個更通用的方法但是該方法可以證明麻煩的爲不同的變量可以有不同的默認值。

+1

我實際上使用這個分頁$ page =(!empty($ _ GET ['page']))? $ _GET ['page']:0;並且當我在頁面上時錯誤消失了,但如果沒有設置頁面,我會收到索引錯誤 – JasonDavis 2009-08-07 00:25:37

+0

,注意空白和isset之間有區別。 – rezzif 2009-08-07 00:49:02

+0

和array_key_exists()。 – 2009-08-07 01:02:42

0

檢查數組元素使用isset的例子( )或空()。

E.g,

if ((!empty($_GET['p'] && $_GET['p'] == "account.edit.topfriends") || 
    (!empty($_GET['action'] && $_GET['action'] == "newmember")) { 
    //some more code here 
} 
+1

我會推薦使用isset,如果值爲0,那麼空值將爲true,並且他詢問如何停止未定義的警告。 – rezzif 2009-08-07 00:11:10

+2

也,你錯過了關閉paren。 – troelskn 2009-08-07 09:21:32

7

由於rezzif提到您需要做的是使用isset()調用進行檢查。如果你使用了很多數組,並且不想返回並添加一堆isset()調用,你可以使用我們的函數。喜歡的東西:

function get_index($array, $index) { 
    return isset($array[$index]) ? $array[$index] : null; 
} 

然後你可以改變你的if語句的東西,如:

if (get_index($_GET, 'p') == "account.edit.topfriends" || get_index($_GET, 'action') == "newmember" || get_index($_GET, 'p') == "account.profile.name") { 
    //some more code here 
} 

如果正在做的所有檢查都反對$_GET你總是可以尼克斯的功能和硬編碼的第一個參數$ _GET在裏面,我的例子假設你正在對幾個不同的數組進行操作。

此解決方案不一定是最優雅的,但它應該完成工作。

+0

謝謝我可以試試這個 – JasonDavis 2009-08-07 00:52:34

+2

+1我喜歡這個答案。讓他可以選擇全線執行。另外一個可能是爲默認值添加可選參數。 函數get_index($ array,$ index,$ default = null){ return isset($ array [$ index])? $ array [$ index]:$ default; } – rezzif 2009-08-07 01:19:37

0

永遠擺脫GET和POST未定義的索引通知!把它放在你文檔的頂部...

<?php 
// Get rid of GET and POST undefined index notice forever! Put this in the top of your document... 
class InputData { 
    function get($p) { 
      return isset($_GET[$p]) ? $_GET[$p] : null; 
    } 

    function post($p) { 
      return isset($_POST[$p]) ? $_POST[$p] : null; 
    } 

    function get_post($p) { 
      return $this->get($p) ? $this->get($p) : $this->post($p); 
    } 
} 
$input = new InputData; 

$page = $input->get('p'); // Look in $_GET 
$page = $input->post('p'); // Look in $_POST 
$page = $input->get_post('p'); // Look in both $_GET and $_POST 
?>