'How to make sure a line of code is executed after a loop ends PHP

I want to execute a line of code behind a foreach but I have to be sure that the foreach has finished. How can I know that? Or is this the default behavior?

Thanks to whoever can help

foreach( $posts as $post ) {
    wp_set_post_terms( $post->ID, $default, 'directory' );
}

$term = get_term_by( 'name', '- Default', 'directory' ); // Run this being sure the foreach has finished.
wp_delete_term( $term->term_id, 'directory' );



Solution 1:[1]

Unless you’re using a specific asynchronous extension (although these extension faked asynchronous mode), PHP runs synchronously and it executes all code and loops before moving to the next operation. So in this case it will complete the loop before moving onto the line AFTER the loop.

In fact, if you script takes too long to complete the loop it will throw a timeout error (depending on your PHP configuration). So if you have 100k iterations, your loop will still complete before moving to the next operation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kissumisha