Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_decode() in PHP not showing true or false statements

Tags:

json

php

I have a response coming back that is JSON encoded, but when I decode it I lose the true/false attributes after using $var = json_decode($response);.

Here’s an example:

{
  "domain": "my.domain.com",
  "created_at": "2014-11-15 00:26:53.74059",
  "valid_mx": true
}

I’ve even tried:

$var = json_decode($response, true);

But it still seems to drop the true/false. How can I properly pull the true/false from the response? What am I missing?

like image 429
MrTechie Avatar asked Jan 16 '15 18:01

MrTechie


3 Answers

This should work for you:

(With this you have the JSON string as an array)

<?php

    $response = '{
                "domain": "my.domain.com",
                "created_at": "2014-11-15 00:26:53.74059",
                "valid_mx": true
            }';

    $var = json_decode($response, true);    

    if($var["valid_mx"] === TRUE)
        echo "true";
    else
        echo "false";

?>

Output:

yes

If you want an object just change this line:

$var = json_decode($response, true);

to this:

$var = json_decode($response);

And then you can access it with this line:

if($var->valid_mx === TRUE)
like image 126
Rizier123 Avatar answered Oct 20 '22 02:10

Rizier123


Your problem is with print_r, not json_decode.

print_r does not show true / false for true / false. Instead, it shows 1 / (blank).

You can use var_dump($var); or var_export($var); instead which will show you the correct values.

like image 28
rjdown Avatar answered Oct 20 '22 03:10

rjdown


This works for me:

if(json_decode($response)->valid_max){
   //your stuff
}
like image 45
mcdonaldjosh Avatar answered Oct 20 '22 02:10

mcdonaldjosh