tags:

views:

1087

answers:

3

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 easiar way to set for example if a page has 50 variables that it is reporting this , is there an easiar 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
}
A: 

Check array elements first using isset() or empty().

E.g,

if ((!empty($_GET['p'] && $_GET['p'] == "account.edit.topfriends") || 
    (!empty($_GET['action'] && $_GET['action'] == "newmember")) {
    //some more code here
}
Andy Baird
I would recommend using isset given that empty will be true if the value is 0 and he asked how to stop the undefined warnings.
rezzif
also, you're missing a closing paren.
troelskn
+6  A: 

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.

rezzif
I actually use this for paging $page = (!empty($_GET['page'])) ? $_GET['page'] : 0; and the error is gone when I am on a page but if no page is set, I get the index error
jasondavis
note there is a difference between empty and isset.
rezzif
And array_key_exists().
Bill Karwin
What an opportunity to use the new shortened ?: operator from PHP 5.3.
tomp
+3  A: 

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.

Steven Surowiec
thanks I might try this
jasondavis
+1 i like this answer. Gives him the option to do it accross the board. One addition might be to add an optional parameter for a default value.function get_index($array, $index, $default=null) { return isset($array[$index]) ? $array[$index] : $default;}
rezzif