Just add the flag JSON_FORCE_OBJECT as the second parameter.
$params = [
"this" => "",
"that" => [],
"and" => "This"
];
json_encode($params, JSON_FORCE_OBJECT);
Gives this
"{"this":"","that":{},"and":"This"}"
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Is there any particular way to declare/initialize an empty associative array?. i know that associative arrays in php is same as array. My problem is when while jsonencoding an this array.
$params = [
'cn' => '',
'op' => '',
'cir' => '',
'adParams' => [ ],
'uid' => '',
'pswd' => '',
];
when i encode this array, json_encode function treats $params['adParams'] as empty array and converts into [] which i don't want it to do.
"{"cn":"","op":"","cir":"","adParams":[],"uid":"","pswd":""}"
but i want this to be like this. here $params['adParams'] == {}.
"{"cn":"","op":"","cir":"","adParams":{},"uid":"","pswd":""}"
One possible way i achieved is this which gave me above string
json_encode([
'cn' => '',
'op' => '',
'cir' => '',
'adParams' => (object)[ ],
'uid' => '',
'pswd' => '',
])
I WANT TO KNOW WHAT IS BEST WAY TO ACHIEVE IT. ANY OFFICIAL FUNCTION OR SOMETHING.
Just add the flag JSON_FORCE_OBJECT as the second parameter.
$params = [
"this" => "",
"that" => [],
"and" => "This"
];
json_encode($params, JSON_FORCE_OBJECT);
Gives this
"{"this":"","that":{},"and":"This"}"
Please or to participate in this conversation.