How to break up php code to avoid echo

You have an extra “}”, there must be two such braces for two for each loops. Also you need to have endif; statement at end after endwhile. Parsing error may be due to extra “}”. Please try below code and let us know if it works.

 <?php
$custom_terms = get_terms('videoscategory');
$other_custom_terms = get_terms('product_category');

foreach ($custom_terms as $custom_term) {
foreach ($other_custom_terms as $other_custom_term) {
    wp_reset_query();
    $args = array('post_type' => 'product', 'orderby' => 'title', 
                'order' => 'asc',
        'tax_query' => array(
  'relation' => 'AND',
'orderby' => 'title', 
                'order' => 'asc',
    array(
        'taxonomy' => 'product_category',
        'field' => 'slug',
        'terms' => $other_custom_term->slug,
'orderby' => 'title', 
                'order' => 'asc',
    ),
            array(
                'taxonomy' => 'videoscategory',
                'field' => 'slug',
                'terms' => $custom_term->slug,
'orderby' => 'title', 
                'order' => 'asc',

            ),
        ),
  );

     $loop = new WP_Query($args);
     if($loop->have_posts()) 
     {
        ?>
        <div class="box <?php echo $custom_term->slug; ?>">
        <h1 style="margin-top:10px;"><?php echo $custom_term->name;?></h1>

      <?php       
      while($loop->have_posts()) : $loop->the_post(); ?>
            <h2><a href="https://wordpress.stackexchange.com/questions/95853/<?php echo get_permalink() ?>"><?php echo get_the_title(); ?></a></h2>
      <?php  endwhile; ?>
      </div>
     <?php   
     }
}
} ?>