PHP encode empty objects in JSON

Posted on Wednesday March 22nd, 2017

Where it is necessary to have PHP's json_encode() function return an empty object, you can simply provide it with an empty object instead...

<?php 
$foo = json_encode(new stdClass);
?>

This can be extended to ensure that associative arrays return empty objects too:

<?php 
$reply['foo'] = new stdClass;
$reply['bar'] = 10;
json_encode($reply);
?>