Drupal reorder a custom hook without changing module weight

Sometimes it is necessary to run a custom implementation of a hook after other modules' implementations have run.
<?php
 
/**
 * Implements hook_module_implements_alter().
 */
function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'thehook') {
    // Move my_module_form_alter() to the end of the list.
    // \Drupal::moduleHandler()->getImplementations()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}
 
/**
 * Implements hook_thehook().
 */
function mymodule_thehook() {
  // ...
}
 
?>

Internal References

External References

Article Type

General