Search code examples
phpnullnotice

PHP: Unidentified Index with NULL value


I've tried everything but just can't get this notice to disappear.

I have a text input that display's the content of $variable which is being grabbed from a database and either has value of NULL or an integer value.

When the value is NULL, and I use this, I get 1 error of unidentified index.

if(isset($data['variable'])) { $variable = $data['variable']; }
else { $variable = numberFormat($data['variable']); } 

When the value is NULL, and I use this, I get 2 errors of unidentified index.

if($data['variable'] == NULL) { $variable = $data['variable']; } 
else { $variable = numberFormat($data['variable']); }

Can anyone shed some light to how to get rid of these "notices"? Thank you!


Solution

  • You might want to see if the $data variable is available. If that is null, then you can't access an element inside a non-existent variable.

    if (isset($data)) {
        if(isset($data['variable'])) { $variable = $data['variable']; }
        else {
            //THIS MAKES NO SENSE. $data['variable'] does not exist.
            //$variable = numberFormat($data['variable']);
            //You can put something else in here, however
            $variable = "";
        } 
    }
    

    Secondly, accessing $data['variable'] when it does not exist is non-sensical because... well I doesn't exist!