php Code for Showing Ads If Heading Else on Bottom

Show google ads when heading4 available otherwise showing ads on bottom of content-

function thekroyaard_ads_heading_4( $content ) {
$ad_code = '
<div class="thekroyaard_ads_heading_3">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxxxx"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>';
if ( is_single() ) {
return ads_insert_after_paragraph( $ad_code, 1, $content );
}
return $content;
}
function ads_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '<h4>';
$paragraphs = explode( $closing_p, $content );
if ($paragraphs) {
$paragraphs[0] = $paragraphs[0].$insertion;
}
return implode( '<h4>', $paragraphs );
}

add_filter( 'the_content', 'thekroyaard_ads_heading_4' );