How to check wp_options’s rewrite_rules if current and existing are the same before flush the rules?

Here’s the trick I’ve been using:

  • Use an array to store the rewrites
  • Hash the array
  • Store the hashed array as an option
  • Check to see if the stored option matches the curret rewrite hash; if not, update the rewrites

Greatly simplified code snippet (this is meant as a starting point, not a finished product):

add_action( 'init', 'wpse_393260_rewrites' );
function wpse_393260_rewrites() {
    // Array of rewrites.
    $my_rewrites = array(
        'foo/([a-z0-9-]+)[/]?$' => 'index.php?foo=$matches[1]',
        'bar/([a-z0-9-]+)[/]?$' => 'index.php?bar=$matches[1]',
        // etc.
    );
    // Implements the rewrite rules.
    foreach ( $my_rewrites as $regex => $query ) {
        add_rewrite_rule( $regex, $query, 'top' );
    }
    // Hashes the $my_rewrites array.
    $hashed_rewrites = md5( serialize( $my_rewrites ) );
    // Gets the currently-active rewrites from the option.
    $my_current_rewrites = get_option( 'my_rewrites_option' );
    // If anything's changed, flush the rewrites and update the option.
    if ( $my_current_rewrites !== $hashed_rewrites ) {
        flush_rewrite_rules();
        update_option( 'my_rewrites_option', $hashed_rewrites );
    }
}