3

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.

4 Answers 4

4

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":{}}
Sign up to request clarification or add additional context in comments.

Comments

3

Cast it to object before encoding:

json_encode((object) $array);

Comments

3

Another answer to this is to use ArrayObject instead of [] when initialising the variable.

The following illustrates the problem. When the associative array is empty, it is JSON encoded as '[]':

$object = [];
echo json_encode($object); // you get '[]'

$object['hello'] = 'world';
echo json_encode($object); // you get '{hello: "world"}'

Instead, keep everything the same, but when you declare the $object, use ArrayObject:

$object = new ArrayObject;
echo json_encode($object); // you get '{}'

$object['hello'] = 'world';
echo json_encode($object); // you get '{hello: "world"}'

The reason this is a good alternative is because using (object) [] converts the variable to an stdClass meaning you have to access the properties using $variable->property. However, if all your existing code was written using $variable['property'], then using (object) [] means you will have to change all of that code, when you can instead just use new ArrayObject.

Link to ArrayObject that has been available since PHP5

Comments

0

Your going to have to check if the array is empty.

if (empty($array_to_dump)) {
    print ':{}';
} else {
    print serialize($array_to_dump);
}

However, the array you get back when you unserialize should be exactly the same either way... an empty array.

Edit: or use the above, even better.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.