Rewrite rules – add_rewrite_rule only works when flush first

I have the following code in my functions.php file. I have a page "projects". I have two types of custom messages: "project" and "project type". An individual project has its own permanent link "/ projects / project-name". The types of projects must display the "projects" page.

My code checks if the URL is a sub-page of "/ projects /". If the subpage is a project type, it loads the template for the projects page (id 8).

if (substr ($ _SERVER['REQUEST_URI'], 0, 11) === & # 39; / projects / & # 39;) {
$ request_subpage = str_replace (& # 39; /, & # 39; & # 39; & nbsp; str_replace (& projects / & # 39;; & # 39;['REQUEST_URI']));
if ($ request_subpage! == & # 39;) {
$ valid_subpage_url = false;
$ project_types = get_posts (array (& # 39; post_type => & # 39; project type & # 39 ;, posts_per_page & # 39; => -1));
foreach ($ project_types as $ project_type):
if ($ project_type-> post_name === $ request_subpage):
$ valid_subpage_url = true;
Pause;
end if;
end of each
// flush_rewrite_rules ();
if ($ valid_subpage_url) add_rewrite_rule ("^ projecten  / $ request_subpage $", "index.php? page_id = 8", & # 39; top & # 39;);

}
}

When I release my comment flush_rewrite_rules (); my code works. When I do not flush the rewrite rules, it does not work (all project type sub-pages return a 404).

What is happening here?