Search code examples
phparraysjsonassociative-arrayempty-list

php serialize empty associative array


I want to dump an associative array to file with 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);