I assign a cookie to a variable:
$user_cookie = $_COOKIE["user"];
How can I check if the $user_cookie
received some value or not?
Should I use if (empty($user_cookie))
or something else?
I assign a cookie to a variable:
$user_cookie = $_COOKIE["user"];
How can I check if the $user_cookie
received some value or not?
Should I use if (empty($user_cookie))
or something else?
If your cookie variable is an array:
If your cookie variable is not an array:
I use this approach.
Try empty function in php http://php.net/manual/en/function.empty.php
You can also use isset http://www.php.net/manual/en/function.isset.php
These are the things empty will return true for:
Taken straight from the php manual
So to answer your question, yes,
empty()
will be a perfectly acceptable function, and in this instance I'd prefer it overisset()
isset()
, however keep in mind, likeempty()
it cannot be used on expressions, only variables.(
isset()
is the way to go, when dealing with cookies)You can use:
but sometimes you want to set if the value is set in the first place
Use isset() like so:
This tells you whether a key named
user
is present in$_COOKIE
. The value itself could be""
,0
,NULL
etc. Depending on the context, some of these values (e.g.0
) could be valid.PS: For the second part, I'd use
===
operator to check forfalse
,NULL
,0
,""
, or may be(string) $user_cookie !== ""
.