Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of hundreds of PHP undefined index notices?

Tags:

php

I just enabled error reporting and wow what a shocker I have probably thousands if not hundreds of notices like this

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

I understand that they are because I am calling a variable withoutsetting it or whatever but is there an easier way to set for example if a page has 50 variables that it is reporting this, is there an easier way to code that page properly to fix them all?

And I don't mean to just hide them I think it would be best to fix them

here is an example of that line I posted

if ($_GET['p'] == "account.edit.topfriends" || $_GET['action'] == "newmember" || $_GET['p'] == "account.profile.name") {
    //some more code here
}
like image 510
JasonDavis Avatar asked Aug 07 '09 00:08

JasonDavis


2 Answers

I usually like to use ternary statements at the top of my scripts to initialise values.


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

Sure you could probably use a more generic approach but that method can prove troublesome as different variables can have different default values.

like image 186
rezzif Avatar answered Nov 11 '22 10:11

rezzif


As rezzif mentioned what you need to do is check with an isset() call. If you're using arrays a lot and don't want to go back and add a bunch of isset() calls you can always us a function. Something like:

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

Then you could change your if-statement to something like:

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

If all the checks being done are against $_GET you could always nix the first parameter of the function and hardcode $_GET in it, my example assumes you're doing this against several different arrays.

This solution isn't necessarily the most elegant, but it should get the job done.

like image 42
Steven Surowiec Avatar answered Nov 11 '22 11:11

Steven Surowiec