Check if a PHP cookie exists and if not set its value

Based on the PHP manual, the existence of a cookie can’t be found.

A reference from the manual: “Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.”

The reason being cookies are response headers to the browser and the browser needs to then send them back along with the next request. This is the reason they are available on the second page load only.

But here is a work around for the same: The $_COOKIE can be set when the setcookie function is called −

if(!isset($_COOKIE['lg'])) {
   setcookie('lg', 'ro');
   $_COOKIE['lg'] = 'ro';
echo $_COOKIE['lg'];