Check if there are any elements with a certain class in the form array of unknown depth I'm new to Drupal and still have to figure out a lot. This might also be just a general programming question.

I wrote a module that has some js-libraries which should be attached to forms on different conditions. For one of those libraries, I want to add it in case the form array has an element with the class "remove-button", which could be at any depth.

I searched for different recursive approaches, but it doesn't work somehow. I was able to attach the library without a condition so it attaches to all forms, so the problem lies within my recursive function.

Snippet from hook_form_alter in my .module file:

function my_module_form_alter(&amp;$form, \Drupal\Core\Form\FormStateInterface &amp;$form_state, $form_id)
{
  // remove-button
  $hasRemoveButton = containsClass($form, 'remove-button');
  if ($hasRemoveButton) {
    $form['#attached']['library'][] = 'my_module/remove-button';
  }
}


Recursive search function (last code I tried):

/**
 * Search a class in $form.
 */
function containsClass($array, $class)
{
  if (!is_array($array)) {
    return false;
  }
  if (isset($array['class']) &amp;&amp; in_array($class, $array['class'])) {
    return true;
  }
  foreach ($array as $subarray) {
    containsClass($subarray, $class);
  }
}


Anyone an idea how this can be achieved? Maybe with a different approach than a recursion?
You can try this for your recursive function.

function containsClass($array, $class) {
  if (is_array($array)) {
    if (in_array($class, $array['class'])) {
      return true;
    }

    foreach ($array as $element) {
      if (containsClass($element, $class)) {
        return TRUE;
      }
    }
  }

  return FALSE;
}


The problem with your function was that it's not returning the result of containsClass() when it's called recursively. However, you only want to return the value if it's TRUE, which is why I added the conditional to check that. Finally, after all items have been looped through, if no TRUE value is found, FALSE should be returned.