改变Imploding和Exploding

This code add ads in the content. I want to change the output. I added new details. I tried on it but I could not solve the problem.

add_filter( 'the_content', 'ads_paragraphs');
function ads_paragraphs( $content ) {

    $adsbeforeparagraph = array(1,3,5);

    global $post;

     $ad = 'ADS CODE';

    $content_expl = explode("<p>", $content);
    for ($i = 0; $i <count($content_expl); $i++ ) {
        if (in_array($i, $adsbeforeparagraph)){
            $content_expl[$i] = $ad . $content_expl[$i];
            }
    } 

     return implode("<p>", $content_expl);
    }

input is here:

<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>

output is here:

<p>ADS CODEtext text text</p>
<p>text text text</p>
<p>ADS CODEtext text text</p>
<p>text text text</p>
<p>ADS CODEtext text text</p>
<p>text text text</p>

I want this output:

ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>

Use like this

       $adsbeforeparagraph = array(1,3,5);

   global $post;

    $ad = 'ADS CODE';
    $content='<p>text text text </p>
                <p>text text text</p>
                <p>text text text </p>
                <p>text text text </p>
                <p>text text text </p>
                <p>text text text </p>';
    $content_expl = explode("<p>", $content);
    for ($i = 1; $i <count($content_expl); $i++ ) {     
        if (in_array($i, $adsbeforeparagraph)){
            $content_expl[$i] ='ADS CODE <p>'.$content_expl[$i].'<p>';
        }
    }
    print_r(implode(" ", $content_expl));

Check this , I've checked this. It works...

Is this what you are looking for?

I use in_array to find out if the current line should have Ads before.
Notice I subtracted 1 from your values since normal arrays count from 0.
If you must have 1,3,5 I can fix that.

$input= "<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>
<p>text text text</p>";

$arr =explode(PHP_EOL, $input);

 $adsbeforeparagraph = array(0,2,4); // subtracted 1 to suit normal array numbering
 $ad = 'ADS CODE';

Foreach($arr as $key => $line){
    If(in_array($key, $adsbeforeparagraph)){ // is this a line that should have Ads?
        Echo $ad . $line . "
";
    }else{
        Echo $line . "
";
    }
}

Output:

ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>
ADS CODE<p>text text text</p>
<p>text text text</p>

https://3v4l.org/8DVua