The reason why we have stdClass is because in PHP there is no way to distinguish a normal array from an associate array (like in Javascript you have {} for object and [] for array to distinguish them).

So this creates a problem for empty objects. Take this for example.

PHP:

$a = [1, 2, 3]; // this is an array $b = ['one' => 1, 'two' => 2]; // this is an associate array (aka hash) $c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

Let's assume you want to JSON encode the variable $c

echo json_encode($c); // outputs => {'a': [1,2,3], 'b': {one: 1, two: 2}}

Now let's say you deleted all the keys from $b making it empty. Since $b is now empty (you deleted all the keys remember?), it looks like [] which can be either an array or object if you look at it.

So if you do a json_encode again, the output will be different

echo json_encode($c); // outputs => {'a': [1,2,3], 'b': []}

This is a problem because we know b that was supposed to be an associate array but PHP (or any function like json_encode) doesn't.

So stdClass comes to rescue. Taking the same example again

$a = [1, 2, 3]; // this is an array $b = (object) ['one' => 1, 'two' => 2]; // this makes it an stdClass $c = ['a' => $a, 'b' => $b]; // this is also an associate array (aka hash)

So now even if you delete all keys from $b and make it empty, since it is an stdClass it won't matter and when you json_encode it you will get this:

echo json_encode($c); // outputs => {'a': [1,2,3], 'b': {}}

This is also the reason why json_encode and json_decode by default return stdClass.