Search code examples
phparraysjsonassociative-arrayempty-list

PHP Serialize an empty Associative Array


I want to dump an associative array to file using PHP. Sometimes the result can be empty and in this case I want the content of the file be exactly : { } so that I can process all files in the same way.

However, I can only initialize a simple array in PHP, and so the output in the file is always this : [ ]. I already tried adding a dummy entry to the associative array and then deleting the entry again so that the array is empty, but then again [ ] is the output in the file.


Solution

  • Cast it to object before encoding:

    json_encode((object) $array);