bg2982
bg2982

Reputation: 69

How to pull individual values out of $_COOKIE["elementValues"]?

I have a JavaScript that saves checkboxes state, puts it into a cookie, and then repopulates my checkboxes in my form. What I am trying to do at this point is put together a bunch of "if statements" with php and then into a string for those that are "true".

Here is what I get when I echo $_COOKIE["elementValues"]. The 1,2,3 represent the id number of each form input checkbox.

   {"1":false,"2":false,"3":false,buttonText":""}

Here is what I am trying to do with PHP.

if ($_COOKIE["1"]=true) 
{ $arguments[] = "AND 2kandunder = 'yes'"; 
}
if ($_COOKIE["2"]=true) 
{ $arguments[] = "AND 2kto4k = 'yes'"; 
} 
if ($_COOKIE["3"]=true) 
{ $arguments[] = "AND 2kandup = 'yes'"; 
}
if(!empty($arguments)) {
$str = implode($arguments);
echo "string: ".$str."<br>;

The problem is I echo my $str and even if all the checkoxes are "false" in the $_COOKIE["elementValues"] it will still echo out AND 2kto4k = 'yes'AND 2kandunder = 'yes'AND 2kandup = 'yes'. How do I write these if statements to add the argument to the string ONLY if that id is "true"?

Here is var_dump($_COOKIE);

array(3) { ["PHPSESSID"]=> string(32) "4b4bbcfc32af2f41bdc0612327933887" [2]=> string(6) ""true"" ["elementValues"]=> string(47) "{"1":false,"2":false,"3":false,"buttonText":""}" } 

{"1":false,"2":false,"3":false,"buttonText":""}

Upvotes: 1

Views: 26

Answers (1)

D4V1D
D4V1D

Reputation: 5849

Edit

As per your comments, looks like $_COOKIE["elementValues"] is a JSON string. You'll have to do as per my edit.


You are doing assignement where you want to do comparison. Here is your corrected code:

First, decode your JSON string:

$cookie = json_decode($_COOKIE["elementValues"], true); // note the second argument to true to make it an associative array

Then, do your conditions, either this way:

if ($cookie["1"] == true) // note the ==
{ 
    $arguments[] = "AND 2kandunder = 'yes'"; 
}
if ($cookie["2"] == true) // note the == 
{
    $arguments[] = "AND 2kto4k = 'yes'"; 
} 
if ($cookie["3"] == true) // note the ==
{
    $arguments[] = "AND 2kandup = 'yes'"; 
}   

Or this way (shorter):

if ($cookie["1"]) // casts variable as boolean if it's not
    $arguments[] = "AND 2kandunder = 'yes'"; 

if ($cookie["2"]) // casts variable as boolean if it's not 
    $arguments[] = "AND 2kto4k = 'yes'"; 

if ($cookie["3"]) // casts variable as boolean if it's not
    $arguments[] = "AND 2kandup = 'yes'"; 

Upvotes: 2

Related Questions