Get an image from the media library. Struggling with the code?

If you want to exit the loop after you find an attachment, use break.

 // Define $programme and pull up $attachments as above
 $attachment_url="";
 foreach ( $attachments as $attachment ) {
     if ($attachment->post_title == $programme) {
         $attachment_url = wp_get_attachment_url($attachment->ID);
         break;
     }
 }

 if ( $attachment_url ) {
     echo $attachment_url;
 } else {
     echo '/images/nontvimg.jpg';
 }