tags:

views:

50

answers:

2

I feel bad about mixing arrays with objects, but I'm not sure that I should.

// Populate array
foreach($participants as $participant){
   $participants[$key]['contestant'] = new Contestant($participant);
   $participants[$key]['brand'] = new Brand($brand);
   $key++;
}

[...]

// Print array
foreach($participants as $participant){
   print "Name: " . $participant['contestant']->name;
   print "Nationality: " . $participant['contestant']->nationality;
}

I'm not comfortable about the $contestant['contestant']->name part. I'd feel better about using objects exclusively.

Is it in fact considered bad practice to mix objects and arrays, or am I obsessing over something that everyone else thinks is fine?

+1  A: 

You're worrying yourself unnecessarily. It's fairly commonplace in other languages to mix sequences/mappings with objects. Arrays are useful when you don't know the number of elements or only a "ragtag" set of elements exist, and objects are useful when you know exactly the number of elements, and said elements each have a specific purpose.

Ignacio Vazquez-Abrams
+2  A: 

It feels fine to me. Where an array makes sense, use an array. Where an object makes sense, use an object.

However, maybe you feel that a participant makes more sense as an object, which, looking at this relatively small code sample, it just may. If so, write up a quick Participant class. If that feels like too much overhead, then don't worry about it. At this point, it's personal preference, since your code, does, in fact, work. It's all about which codebase you would prefer to be working with in the future.

Matchu