1

PHP's syntax to create an array (either indexed or assosiative) is the same, aka

$arr = [];

However, json_encode will convert an empty PHP "array" (note the quotes) to an empty JS array ([]), which is not desirable in certain situations.

Is there a way I can create an empty assosiative array in PHP, so json_encode will convert it to an empty JS object, aka {}, instead of [].

0

3 Answers 3

2

You can use stdClass:

$obj = new stdClass();
echo json_encode($obj);

This gets me the intended {} output.

Sign up to request clarification or add additional context in comments.

Comments

2

Use a stdClass():

php > $x = new StdClass;
php > echo json_encode($x);
{}

Of course, once it's a stdclass, you wouldn't be able to use it as an array anymore. But this is at least one way of forcing an empty object in JSON, so you could just special-case your code:

if (count($array) == 0) {
   $json = json_encode(new StdClass);
} else {
    $json = json_encode($array);
}

2 Comments

Juuuust beat me by a second, dang. :)
Let me try how much MongoDB will tolerate that :)
2

You can just pass the JSON_FORCE_OBJECT option to the json_encode function. This will force any empty arrays to be objects as well.

JSON_FORCE_OBJECT (integer) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. Available since PHP 5.3.0.

So:

if (empty($array)) {
    $json = json_encode([], JSON_FORCE_OBJECT);
} else {
    $json = json_encode($array);
}

This looks cleaner than converting an object in my opinion.

Or even

$json = json_encode($array, empty($array) ? JSON_FORCE_OBJECT : 0);

4 Comments

Didn't know that--very handy!
Yeah, that that would make to real empry arrays to get convert to empty Objects too, which is not something I want to do.
A conditional could be used to solve that issue, but I understand.
@alexandernst Added the conditional that is required like the other solutions.

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.