1

In a PHP course, an example of an Associative Array is:

$myAssocArray = array('year' => 2012,
                    'colour' => 'blue',
                    'doors' => 5);

Is that a good example of an Associative Array? Why use an Array for this car, and why not use an Object? I thought arrays weren't used to list an object's properties, but rather for collections of similar values.... such as:

$numberStudents = array('firstgrade' => 78,
                    'secondgrade' => 84,
                    'thirdgrade' => 76);

Thanks!

Rounin
  • 27,134
  • 9
  • 83
  • 108
Jonathan
  • 151
  • 1
  • 8
  • Aren't those both arrays? Here's a discussion already on this topic, http://stackoverflow.com/questions/2056931/value-objects-vs-associative-arrays-in-php. – chris85 Mar 11 '15 at 02:43
  • 1
    I think it all depends on what you're trying to achieve. If your program is about manipulating cars, then I could see using objects regarding cars, but if your program is about something else where a car accounts for only a small part of the program then an associative array is better. Can you elaborate more on the application? What do you want to achieve in the end with the use of the object/array? –  Mar 11 '15 at 02:44
  • @chris85 yes the code is arrays but from what I gather, the first array is about a car and he is asking if its better to use that to describe a car or to write a whole object about one. –  Mar 11 '15 at 02:46
  • Thanks Mike. Here's an example, let's say I need to store my database credentials for a web app: $host = 'example.org'; $username = 'myuser'; $password = 'mypass'; There's only one set of credentials since there's only a single database. Is it better to use an Associative Array or an Object for that? Thanks! – Jonathan Mar 11 '15 at 02:49
  • Yup, you are correct @Mike. My mistake, read to quickly. – chris85 Mar 11 '15 at 02:49

1 Answers1

1

When you're creating your own objects/arrays to store data I believe it's a matter of preference.

My only preference is not to nest arrays within objects and vice-versa as my recent experience with an API slowed down to a snail's pace when trying to check if I need to call an index or a property traversing down 10 levels...

If you're talking about objects that contain classes/are closely tied to the database or using frameworks which provide you those objects, usually you have many helper methods inherited which allow setting/getting properties, accessing formatting functions, export functions, and many other 'goodies' that their authors forced down your throat.

In those situations obviously the objects serve a specific purpose.

My preference is to work with non-associative arrays and avoid all foreach loops as best as I can.

Vladimir Ramik
  • 1,920
  • 2
  • 13
  • 23