2012-04-28 133 views
-2
if ((!$_GET['month']) && (!$_GET['year'])) { 
    $month = date ("n"); 
    $year = date ("Y"); 
} else { 
    $month = $_GET['month']; 
    $year = $_GET['year']; 
} 

它顯示Notice: Undefined index: month in....在PHP中修復「未定義索引」錯誤

我知道,如果我用error_reporting(null);上面的代碼,該通知將不會出現,但有沒有辦法解決這個問題?

+2

'isset''array_key_exists'和'empty'是你的朋友。 [:「注意:未定義變量」和「通知:未定義的索引」 PHP]的 – Corbin 2012-04-28 08:25:03

+0

可能重複(http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Corbin 2012-04-28 08:26:33

回答

2

如果數組元素不存在,你會得到通知,因爲您要訪問一個不存在的元素。您需要使用isset()empty()來檢查它(這些不是函數,而是語言結構,因此不會考慮訪問這些元素)。既然你可能從來沒有空/零年/月,empty更有意義;但您也可以使用!isset(),然後使用0,並且也允許使用空字符串。

if(empty($_GET['month']) || empty($_GET['year'])) { 
    $month = date('n'); 
    $year = date('Y'); 
} 
else { 
    $month = (int)$_GET['month']; 
    $year = (int)$_GET['year']; 
} 

但是,它可能會更有意義分別檢查這兩個變量:

$month = empty($_GET['month']) ? date('n') : $_GET['month']; 
$year = empty($_GET['year']) ? date('Y') : $_GET['year']; 
+0

顯示如何正確地做他想要的邏輯可能是好的。 if(!empty(...)&&!(empty(...)){$ month = ...; $ year = ...;} else {$ month = date('n'); $ year = DATE( 'Y');}' – Corbin 2012-04-28 08:30:53

+0

$月=空(INTVAL($ _ GET [ '月']))日期( 'N'):$ _GET [ '月']; – askovpen 2012-04-28 08:41:53

+0

@askovpen INTVAL總是返回在至少(INT)0,所以它永遠不會是空的 – 2012-04-28 08:45:20

0

您必須使用empty()isset()來檢查是否已定義變量。

if (empty($_GET['month']) || empty($_GET['year'])) { 
    $month = date ("n"); 
    $year = date ("Y"); 
} else { 
    $month = $_GET['month']; 
    $year = $_GET['year']; 
} 
+0

檢查你的邏輯。如果月份是空的而不是年份呢?巴姆。未定義的索引'月'。 – Corbin 2012-04-28 08:24:45

+0

呵呵,你是對的,並且是固定的。 – Nadh 2012-04-28 08:25:39

0
$month = date('n'); 
$year = date('Y'); 
if (isset($_GET['month'])) { 
    $month=$_GET['month']; 
} 
if (isset($_GET['year'])) { 
    $year=$_GET['year']; 
} 
+0

你的代碼有同樣的問題NADH的。 – Corbin 2012-04-28 08:26:04

+0

是的,只要我發佈它就已經實現了。現在更正 – gopi1410 2012-04-28 08:29:49

+0

仍然有問題。如果設置了月份和年份,則僅設置月份。 (和一個不匹配的'('在線3和5) – Corbin 2012-04-28 08:29:50

0

是的,你可以在使用if(isset($_GET['month']) && isset($_GET['year']))你如果塊

+3

呃,謝謝下面的答案? – ThiefMaster 2012-04-28 08:28:22

1

您當前擁有它的方式是同時檢查,如果一個失敗都改變,也許最好預先設定月份&日期,然後在params通過時更改。另外,檢查那裏的數字是個好主意。否則一個字符串可能會進一步破壞你的代碼

<?php 
$month = date ("n"); 
$year = date ("Y"); 
if (isset($_GET['month']) && is_numeric($_GET['month'])) { 
    $month = $_GET['month']; 
} 
if (isset($_GET['year']) && is_numeric($_GET['year'])) { 
    $year = $_GET['year']; 
} 

//Or better yet 
$month = (isset($_GET['month']) && is_numeric($_GET['month']))?$_GET['month']:date("n"); 
$year = (isset($_GET['year']) && is_numeric($_GET['year']))?$_GET['year']:date("Y"); 
?>