Programmatically remove one field value out of many for the user object

Public

Only remove one of the fields by value out of an unlimited user field. Here we are removing the user as a contact and re-saving the user object programmatically.

Get raw version
php
  1. function api_remove_contact_save($remove_contact_uid) {
  2. global $user;
  3. $my_user = user_load($user->uid);
  4. $contactUid = (int)$remove_contact_uid;
  5.  
  6. if(!empty($my_user->field_my_contacts)) {
  7. $contactsArray = $my_user->field_my_contacts;
  8. $newArray = array();
  9. foreach ($contactsArray['und'] as $key => $value) {
  10. if($value['value'] !=$remove_contact_uid) {
  11. $newArray['und'][]['value'] = $value['value'];
  12. }
  13. }
  14.  
  15. $edit = array(
  16. 'field_my_contacts' => $newArray
  17. );
  18. user_save($my_user, $edit);
  19. }
  20.  
  21. $destination = 'transfer/new/users';
  22. drupal_goto($destination);
  23.  
  24. //return print_r($edit);
  25. }