Objects and Associative Arrays

JavaScript does not have associative arrays. When you use an associative array notation in JavaScript you are actually working with an object. JavaScript provides two alternative notations for interacting with Objects that can be used interchangeably one of which just happens to look a bit like the associative array notation used in some other languages.

PHP is one of the languages hat does support associative arrays. This means that you cannot use the object and array notations interchangeably in PHP the way you can in JavaScript.

To define an object with a property in PHP you would use code such as:

$o = new stdClass();
$o->foo = 'foo';

To define an associative array with a key/value pair in PHP you would use code such as:

$a = [];
$a['foo'] = 'foo';

To get the names (and values) of the properties of an object you would use:


This in effect converts the object into a single dimensional associative array (retaining the objects for any additional dimensions).

To get the keys of the associative array you would use:


You can also get all the values of the associative array using:


One way where associative arrays differ from objects in PHP is that associative arrays in PHP the keys have an order just as regular arrays do and all of the same functions that work for regular arrays also work for associative arrays. The only difference between the two types of array is whether the keys are integers or strings. You also need to be aware that only those strings that cannot be cast to an integer will be processed as strings.

The other way where objects and associative arrays differ is that objects support inheritance, polymorphism, type hinting, encapsulation etc which arrays (regardless of their type) do not support.

While objects and associative arrays do have these differences in PHP, it is still easy enough to convert between them in order to take advantage of the features of both. In fact the simplest commands for doing the conversions are very similar.

$array = json_decode(json_encode($object), true);
$object = json_decode(json_encode($array), false);


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow