Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
nico1510 Avatar asked Feb 10 '26 23:02

nico1510


1 Answers

The json_encode function has an option that will coerce arrays into objects where ever contextually appropriate - i.e. associative arrays but this also includes empty arrays, for example:

$array = array(
    'foo' => array(),
    'bar' => array()
);

echo json_encode($array, JSON_FORCE_OBJECT);  // {"foo":{},"bar":{}}
like image 153
Emissary Avatar answered Feb 12 '26 15:02

Emissary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!