The function field_get_items is supposed to only return an array or FALSE, however on php 5.3 it can return a string.

For reference, I'm running on a 64 bit ubuntu server 12.04 with php 5.3.10 from the repo. This is not based on internal drupal behavior, and we can look at an example without bootstrapping drupal.

$field_name = 'body';
$entity = new stdClass();
$entity->{$field_name} = 'Stub body';
$langcode = 'en';

var_dump(isset($entity->{$field_name}[$langcode]) ? $entity->{$field_name}[$langcode] : FALSE);

The code above on php 5.3.10 returns 'S'.

Therefore, the function field_get_items will return a string instead of an array or false.

However, the return value for function field_get_items is stated as "An array of field items keyed by delta if available, FALSE otherwise". This means that either the function field_get_items or the return value is stated incorrectly. I believe it's incorrect and unexpected behavior for function field_get_items to return a string. Therefore I propose the function field_get_items look like the following.

/**
 * Returns the field items in the language they currently would be displayed.
 *
 * @param $entity_type
 *   The type of $entity; e.g., 'node' or 'user'.
 * @param $entity
 *   The entity containing the data to be displayed.
 * @param $field_name
 *   The field to be displayed.
 * @param $langcode
 *   (optional) The language code $entity->{$field_name} has to be displayed in.
 *   Defaults to the current language.
 *
 * @return
 *   An array of field items keyed by delta if available, FALSE otherwise.
 */
function field_get_items($entity_type, $entity, $field_name, $langcode = NULL) {
  $langcode = field_language($entity_type, $entity, $field_name, $langcode);
  if (isset($entity->{$field_name}[$langcode]) && is_array($entity->{$field_name}[$langcode])) {
    return $entity->{$field_name}[$langcode];
  }
  return FALSE;
}

I've added a patch based on the latest 7.x branch.

Comments

roberttstephens’s picture

Title: The function field_get_items can return a string. It should only return an array of FALSE. » The function field_get_items can return a string. It should only return an array or FALSE.

Fixing a typo in the title.

mgifford’s picture

Assigned: roberttstephens » Unassigned

The function field_get_items doesn't exist in D8, so I assume this problem doesn't need to get fixed there first.

The patch still applies. What is the best way to test this?

David_Rothstein’s picture

Status: Needs review » Postponed (maintainer needs more info)
$entity = new stdClass();
$entity->{$field_name} = 'Stub body';

Under what conditions would an entity ever look like that? Doesn't the field API always attach fields as arrays?

Status: Postponed (maintainer needs more info) » Closed (outdated)

Automatically closed because Drupal 7 security and bugfix support has ended as of 5 January 2025. If the issue verifiably applies to later versions, please reopen with details and update the version.