0

check wether cookies are available or not

$d=0;
//**data is stored in cookies as arrays**
if(is_array($_COOKIE['data']) {
    //**data increment by 1 if found**
    $d=$d+1;
}
//**if data not found echo data not found**
if($d==0) {
    echo "data is not present";
}
else{
    echo "data presrnt";
}

I am getting notice undefined variable data

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
karthik.u
  • 3
  • 4
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – Jonnix Aug 07 '17 at 16:54
  • change `is_array` to `isset` and you forgot a `)` at the first if. – Deblugger Aug 07 '17 at 17:00

2 Answers2

0

use isset to check vars set or not:

$d=0;
//**data is stored in cookies as arrays**
if(isset($_COOKIE['data']))
    if(is_array($_COOKIE['data']){
    //**data increment by 1 if found**
        $d=$d+1;
    }
//**if data not found echo data not found**
if($d==0){
echo "data is not present";
}
else{
echo "data presrnt";
}
aidinMC
  • 1,415
  • 3
  • 18
  • 35
0

you can check the existance of a variable with isset() function like this :

if(isset($_COOKIE['data']) && is_array($_COOKIE['data']){
  echo "data present";
} else{
  echo "data is not present";
}

you can also check if a variable exist and not empty with empty() function like this :

if(!empty($_COOKIE['data']) && is_array($_COOKIE['data']){
  echo "data present and it's not empty";
} else{
  echo "data is not present";
}

empty values are : null, "", 0, "0", 0.0, false, [], $var// undeclared var

also i see that your storing an array in the cookie, i suggest for best practice serializing the array before storing in a cookie like this :

setcookie('data', serialize($data), time()+3600);

to get it's value all you have to do is :

$data = !empty($_COOKIE['data']) ? unserialize($_COOKIE['data']) : null;
yoeunes
  • 2,927
  • 2
  • 15
  • 26