'Undefined index while checking for COOKIE in PHP

I set a cookie on a visitor's PC to show a notice once every 24 hours. Recently I started getting the following error in my error log:

PHP: undefined index notice in **

I use the following code to check if the cookie exists with value and if not show notice:

if($_COOKIE['notice'] != 'yes')  
   echo 'notice';
}

I can use the following to avoid the PHP notice:

if((isset($_COOKIE['notice']) || !isset($_COOKIE['notice'])) && $_COOKIE['notice'] != 'yes')

Is there a way to do this check in one step only like I was doing or in a similar way?

Thanks



Solution 1:[1]

You always need to know if a variable is set before try to find what is inside, so yes.. you need to do the check. Also, your logic is wrong.. you are checking if notice is or isn't set (allways true) and checking if notice is "yes".

The code should be something like this:

if ( (!isset($_COOKIE['notice'])) || ( (isset($_COOKIE['notice'])) && ($_COOKIE['notice'] != 'yes') ) ) {
  //Show the notice
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1