user11827463
user11827463

Reputation: 47

Why is this json value not a PHP array key?

When parsing the json below, the PHP statement:

if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {

never evaluates to true despite that "Demo" is a "key" as shown from the print_r statement.

What am I doing wrong on how I'm testing to see if "Demo" or "Live" actually exists in the json? (one or the other or both may be there for any given record)

Thank you.

Json:

{
  "MinimumVersion": "20191101",
  "Guids": {
    "0ebe7e53-12fc-4f8f-a873-4872fe30bbee": {
      "Broke": {
        "Yes": {
          "Demo" : { "Expires" : "" },
          "Live" : { "Expires" : "" }
        },
        "No": {
          "Demo" : { "Expires" : "20191104" },
          "Live" : { "Expries" : "" }
        }
      },
      "Message": "You need to upgrade to the latest version."
    }
  }
}

PHP:

<?php
$string = file_get_contents("json.txt");
$json_a = json_decode($string,true);

$g = "0ebe7e53-12fc-4f8f-a873-4872fe30bbee";
$b = "No";
$a = "Demo";

echo "G: \"" . $g . "\"<br>";
echo "B: \"" . $b . "\"<br>";
echo "A: \"" . $a . "\"<br>";

if (is_array($json_a["Guids"][$g]["Broke"][$b][$a])) {
    #This next line prints Array ([0] => Expires )
    print_r(array_keys($json_a["Guids"][$g]["Broke"][$b][$a]));
} else {
    echo "Test: false";
}

if (array_key_exists($g,$json_a["Guids"])) {
    echo ("true1");
    if (array_key_exists($b,$json_a["Guids"][$g]["Broke"])) {
        echo ("true2");
        if (array_key_exists($json_a["Guids"][$g]["Broke"][$b][$a])) {
            #this never evaluates to true. Why? "Demo" is a "key" as shown from the print_r results statement above.
            echo "Value:\"" . $json_a["Guids"][$g]["Broke"][$b][$a] . "\"<br>";
        }
    }    
}

?>

Upvotes: 0

Views: 47

Answers (1)

Nick
Nick

Reputation: 147206

You're not using array_key_exists properly for that particular case (you use it correctly elsewhere). The correct usage is

array_key_exists ( mixed $key , array $array )

so for what you want to check, you should use

array_key_exists($a, $json_a["Guids"][$g]["Broke"][$b]);

Upvotes: 2

Related Questions