Can't get $_COOKIE[''] inside PHP function

I have a custom WordPress plugin that I developed.

Inside it I have 2 functions:

function A (){
   B ();

function B (){
   $result = "XXX" . $_COOKIE['mtc_id'] . "XXX";
   return $result;

echo $_COOKIE['mtc_id'];

Why is my $_COOKIE['mtc_id'] null in function B () ($result = “XXXXXX”) whereas when I echo $_COOKIE['mtc_id'] I get my desired cookie value?

I’m sure it’s something very basic but I am missing it. I even tried to define it outside and use the variable inside the function but still in vain.

Of course, my cookie is of same domain and as mentioned, if I echo it, it gives me the required string.

Also, the cookie is already set because function A () is trigered way after the cookie is loaded. I have simplified the code to the maximum.

The $_COOKIE variable is a standard array. It can be used the same as any other array.
BUT, you need to learn about PHP “SCOPE”. Any variables inside a function must be declared.
Therefore, you are using an array that is not inside the “GLOBAL” scope of variables.
You would need to declare the array as global. Either inside each function that uses it or global to
your entire page. So, your $_COOKIE array does not exist inside ANY function.
Here is a simple page to explain it. PHP Scope

Sponsor our Newsletter | Privacy Policy | Terms of Service