Writing to a specific or new element in a multi-value custom field We're trying to key track of software license keys issued to a specific user in Drupal 7.  We've created a custom user field called "field_key" with unlimited values.  We'd like to add a new element to field_key every time a new license is issued, and save the new key into the new element.

As expected, the following code saves our new key into the first element of the array every time, overwriting the original:

$edit['field_key'][LANGUAGE_NONE][0]['value'] = $key_save;
user_save($account, $edit);


If we remove the index value, changing [0] to [], what I thought should happen was that the index would be incremented and we'd write to the next element.

$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);


That ends up behaving exactly like the first example using [0], overwriting the original.

If I force the index (delta) value, using [1], for example, the result is the same. This occurs even if I create a new empty element in the user GUI.  I can add additional elements and populate them in the GUI.  If I do this and have, say, 5 keys listed in the user GUI, the next time we run the code using [], [0] or [5], the result is that all of the original elements are deleted, the field is reduced to a single element, with the new value overwriting the original.

I obviously have the command syntax wrong here.  Any tips?
You're nearly spot on, the only problem is whatever field array you put in $edit will overwrite the array that's in there now; no merging happens behind the scenes. This is probably the correct behaviour as you should be able to overwrite the field completely if you need to.

At the moment each time you use

$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);


The field is being re-initialised as whatever's in $edit['field_key'], i.e. a single element.

To append to the array you could do something like this:

$field_items = $account-&gt;field_key;
if (!is_array($field_items)) {
  $field_items = array();
}

$field_items[LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, array('field_key' =&gt; $field_items));