2009-08-07 36 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 
?>