2

I came across this problem when trying to decode json into an array, for instance,

it works fine like this,

$year = 2012;
$month = 3;

$json = '{"year":'.$year.', "month":'.$month.'}';
$config = json_decode($json,true);

var_dump($config); // return array.

but if I set one of the variable to null, for instance,

$year = 2012;
$month = null;

$json = '{"year":'.$year.', "month":'.$month.'}';
$config = json_decode($json,true);

var_dump($config); // return null

I am after this result,

array
  'year' => int 2012
  'month' => null

How can I return such result then?

Run
  • 54,938
  • 169
  • 450
  • 748

1 Answers1

3

That's because when you do

$json = '{"year":'.$year.', "month":'.$month.'}';

results in:

{"year":2012, "month":}

Which in itself is not a valid json, thus you are getting NULL, if you can help it do

$month = "null"

I got the following code:

$year = 2012;
$month = "null";

$json = '{"year":'.$year.', "month":'.$month.'}';
echo $json . "\n";
$config = json_decode($json,true);
var_dump($config);

results:

{"year":2012, "month":null}
array(2) {
  ["year"]=>
  int(2012)
  ["month"]=>
  NULL
}
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123