Avoiding Undefined Index

The PHP book I read has a debugging script in it that is set to detect all erros and plaster them on the screen.

However, I keep getting pages of erros related to…


An error occurred in script ‘/Users/user1/Documents/DEV/+htdocs/SeminarRegistration/103_SignIn.php’ on line 17: Undefined index: email


What is the best way to prevent this “Notice”??

One thing I find annoying about PHP is an inability to define variable types?! Is there a way to at least initialize variables if you can’t “type” them??

Thanks,

Amy

Not sure I’m totally following but it sounds like your referencing and array index that does not exist

I am assigning form values to variables, like…

$name = $_POST[‘name’];

Amy

Okay in that case $_POST[‘email’] does not exist

You actually have to check to see if the key exists with isset($_POST[‘email’]) (isset() is special – it won’t throw the notice). It’s kind of lame and stupid, but that’s PHP for you. You can wrap it in a function/method to make it less annoying, or fill the respective array with missing keys.

There is no variable initialization (except fields in classes). You can only set a variable.

Note: Setting a variable to NULL in PHP does not delete that variable, unlike some dynamic languages.

Also, you can disable notices altogether, although that may make it harder to catch variable typos.

I do something like this:


$name = isset($_POST['name'] ? $_POST['name'] : null);

If you want to avoid this type of error you can test:
if(array_key_exists($key, $array){
// do your stuff with $array[$key]
}

This is the truth.


<?php
    if(array_key_exists('email', $_POST)){
        /* do something awesome */
    }
?>

I wrote this little ditty…


[COLOR="blue"]  // FUNCTION: Handle POST values.
  function input_post($name, $default = NULL) {
    return isset($_POST[$name]) ? $_POST[$name] : $default;
  }

[COLOR="DimGray"]/*
  // Define variables.
  $email = $_POST['email'];
  $new_cust = $_POST['new_cust'];
  $password = $_POST['password'];
  $submitted = $_POST['submitted'];
*/[/COLOR]

  // Define variables.
  $email = input_post('email');
  $new_cust = input_post('new_cust');
  $password = input_post('password');
  $submitted = input_post('submitted');

  echo 'email = ' . $email . "<br />";
  echo 'new_cust = ' . $new_cust . "<br />";
  echo 'password = ' . $password . "<br />";
  echo 'submitted = ' . $submitted . "<br />";[/COLOR]

Will that solve my problem?? :-/

(It seems to work when I re-run my form?!)

Also, are you saying that I cannot initialize variables in PHP??

If so, that is super lame!!

So I couldn’t do this?

$name = "";
$age = NULL;
$income = 0;

Amy

Yes you can. You can:


<?php
    if (!isset($_POST['email']){$_POST['email'] = ''};
?>

No, you can do that. But that’s no different from setting the variables a different value, syntactically.

There may be a better way to do this, but heres an idea:
You could put each one on one line to make it shorter.


if (isset($_POST['name'])) 
{ 
      $name = $_POST['name']; 
} 
else {
      $name = NULL 
}


if (isset($_POST['email'])) 
{ 
      $email= $_POST['email']; 
 } 
else 
{ 
      $email= NULL 
}

If you can install the class HTTP extension (from pecl, it’s called pecl_http), then you can use HttpQueryString class and can handle request vars in much better way:

$oRequest = HttpQueryString::singleton();
$email = $oRequest->get(‘email’, HttpQueryString::TYPE_STRING);

This will return the value of POST or GET ‘email’ value or null if it’s not set. The nice thing is that you can define a default ‘fallback’ value in case the param is not set:
$email = $oRequest->get(‘email’, HttpQueryString::TYPE_STRING, ‘default@email.com’);

So you will never get the undefined index when using this class to access request variables.

I’ve seen someone handle undefined variables and indexes with a custom getIfSet() function. If I recall correctly, it took a variable (e.g. $test, $test[‘key’]), and an optional default value. Within the function it did a isset(), and if it was set, would return it’s value, otherwise returning the null or the optional default value.

It would have looked something like this…


function getIfSet (&$var, $defaultValue = null)
{
	if(isset($var))
		return $var;
	else
		return $defaultValue;
}

I’m not saying that’s the best solution, but it’s A solution. Generally speaking though, global helper functions in an OO application are not recommended as objects become dependant on them, and as a result less portable. It’s important however not to forget the reason this notice exists. It exists to assist in debugging, by alerting you of undefined variables which may be causing unpredictable behaviour, so only use checks such as isset() and getIfSet() if it’s expected that the variable may not be defined. Using such checks anywhere else creates messy convoluted code, and defeats the point of having this notice.