In PHP, I noticed that if I have an array and then json_encode() it, the boolean values get converted to true and false. However, I want them to be converted to 1 and 0, respectively.
Here’s an example:
$data = Array("foo" => true, "bar" => false, "baz" => false, "biz" => true);
print json_encode($data);
The above outputs:
{"foo":true,"bar":false,"baz":false,"biz":true}
However, if true and false were 1 and 0 instead, we could have a shorter string, which would take less time to transfer over the Internet:
{"foo":1,"bar":0,"baz":0,"biz":1}
How can I make PHP encode JSON using 1 and 0 instead of true and false?
I figured it out. You can use the
array_walkorarray_walk_recursivefunction in PHP to cast the booleans to integers before encoding the JSON. I wrote a function to do that:Here’s a demonstration script:
The script outputs: