Properly Getting Field Data on Entities (Nodes)

When I first started using Drupal 7 I was in the habit of typing $node->field_foo[0] (the Drupal 6 syntax IIRC). I looked at porting this philosophy to Drupal 7 like so many others and ended up at $node->field_foo[LANGUAGE CODE] to get the array of field values. Isn't that ugly? Are you still doing this? If you are then it's the wrong way and using code like this should be discouraged. Yet, just last week I was talking to someone whose still doing this. It's a rather common practice. So, if you do write code like this let's explore a better way.

This all starts with a new function to Drupal 7 called field_get_items(). This function is designed to get the items while handling the language for you. It works for entities beyond just nodes as well. An example use would be:

$items = field_get_items('node', $node, 'field_foo');

As an optional 4th argument you can pass in the language code if you are looking for a specific language.

If you look inside field_get_items() you'll see that it handles the language for you. This function can also be used on any field of any fieldable entity.

Though, if what you're trying to do is style the output of the field you might be better off writing a field formatter.

Special thanks to Dave Reid who was the original person to teach me about this function a lot time ago.