Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rajeshtva's avatar

How to declare empty associative array?

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.

0 likes
4 replies
Tray2's avatar
Tray2
Best Answer
Level 73

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"}"
rajeshtva's avatar

@tray2 what if i have mixed use cases?. like this. in the json encoded string.

json_encode([
            'cn' => '',
            'op' => '',
            'cir' => '',
            'adParams' => [ ], // this is to be an object
            'uid' => '',
            'pswd' => '',
			'categories' => [] // this remains an array 
        ]);

and the output i am expecting is

"{"cn":"","op":"","cir":"","adParams":{},"uid":"","pswd":"","categories":[]}"
Tray2's avatar

@rajeshtva I suggest you give it a try, and then read the docs for json_encode.

rajeshtva's avatar

@tray2 i did read the docs. but it doesn't seem to mention the last particular case. even the first case was not mentioned properly. But since my method is working nicely till now. Your suggestion was cherry on top. I am fine. I was just being curious. Thanks.

1 like

Please or to participate in this conversation.