0

I'm trying to store the value of ok in a variable starting from a json file but the output isn't what I'm expecting it to be.
Here's my code:

$messaggio = '{"ok":false,"error_code":400,"description":"Bad Request"}';
$messaggio = json_decode($messaggio, true);
print_r($messaggio);

Output: Array ( [ok] => [error_code] => 400 [description] => Bad Request)

Shoudn't it be like this? Array ( [ok] => false [error_code] => 400 [description] => Bad Request)
And if it shouldn't, how can I store the value of ok in a variable?

Seba
  • 7
  • 2
  • 1
    Try `var_dump`. – tkausl Jun 30 '22 at 09:01
  • It returns me this `array(3) { ["ok"]=> bool(false) ["error_code"]=> int(400) ["description"]=> string(34) "Bad Request" }`, how to store it? – Seba Jun 30 '22 at 09:02
  • What do you mean by `store` it? Its strored in your `$messaggio` variable. – tkausl Jun 30 '22 at 09:03
  • Sorry, I meant how to access to the value of `ok` – Seba Jun 30 '22 at 09:04
  • `$messaggio["ok"]`? – tkausl Jun 30 '22 at 09:05
  • 1
    A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values. [Why does this false value convert to empty string instead of 0?](https://stackoverflow.com/questions/54858771/why-does-this-false-value-convert-to-empty-string-instead-of-0) – IT goldman Jun 30 '22 at 09:05
  • My advice is to use 0 or 1, because Booleans behave unexpectedly when using Ajax for example. – IT goldman Jun 30 '22 at 09:08
  • @ITgoldman How do they "behave unexpected with AJAX"?! Especially when properly going through JSON, they behave very predictably… – deceze Jun 30 '22 at 09:11
  • @deceze Not sure I remember. But I had issues with jQuery ajax and boolean values, trying to send an `object`. I had to finally convert to JSON. so It's not like I said. sorry. Still it has potentially some issues when in some situation `false` becomes `"false"`. – IT goldman Jun 30 '22 at 09:19
  • @ITgoldman That only happens if you don't treat your data properly. Booleans don't randomly turn into strings. – deceze Jun 30 '22 at 09:22

1 Answers1

0

This is the content of a script copied here and pasted in a php script:

$messaggio = '{"ok":false,"error_code":400,"description":"Bad Request"}';
$messaggio = json_decode($messaggio, true);
print_r($messaggio);
var_export($messaggio['ok']);

As you can see, ... I've added var_export function to export the value.

Array
(
    [ok] =>
    [error_code] => 400
    [description] => Bad Request
)
false

If you see nothing, it doesn't means that there is nothing.

I've also tried to show you a little example with interactive shell.

php -a
Interactive shell

php > $variabile = false;
php > echo $variabile;
php > var_export($variabile);
false

If you want to go deep into the content of a variable. Use var_export or var_dump functions.

sensorario
  • 20,262
  • 30
  • 97
  • 159