Hi I have made a custom module to alter the address module form. It works well for one field, however I am stuck trying to use a for each loop in recursively calling this to as many elements there are.

My current code is as such:

function address_custom_address($element, $form_state) {
  $element[0]['address']['given_name']['#title'] = t('Base Name');
  $element[1]['address']['given_name']['#title'] = t('Base Name');
  $element[2]['address']['given_name']['#title'] = t('Base Name'); 
  return $element;

this works, however as you can tell it is redundant and does not satify cases in which the user creates more than 3+ addresses.

I tried to use a foreach loop

foreach($element as $value){
   $title = $value['address']['given_name']['#title']; //this is the title of each element
   //assert title not null
   if(isset($title)) {

      //this is the error it gives me
      $value['address']['given_name'] = array(
       '#title' => 'Base Name',

Error: Cannot use string offset as an array

If anyone has references to where i can better understand this, that would be very helpful. Thank you.

1 Answer 1


You're on the right track, but doing it slightly incorrect. You can use this:

function address_custom_address($element, $form_state) {
  $i = 0;
  while (isset($element[$i)) {
    $element[$i]['address']['given_name']['#title'] = t('Base Name');


  return $element;
  • That worked! I didn't think of doing a while loop, wow. Thanks a lot. Commented Mar 6, 2020 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.