Niels Hermann
Niels Hermann

Reputation: 538

PHP replace every 2nd

<?php
        $fact_BB = array("[start]", "[mid]", "[end]");
        $fact_HTML   = array("<tr><td class='FactsTableTDOne'><p>", "</p></td><td class='FactsTableTDTwo'><p>", "</p></td></tr>");

        $str_Facts = str_replace($fact_BB, $fact_HTML, $row['facts']);

        echo $str_Facts;
    ?>

Is it possible to switch between 2 $fact_HTML?

1. $fact_HTMLone = "code";
2. $fact_HTMLtwo = "code";
3. $fact_HTMLone = "code";
4. $fact_HTMLtwo = "code";
5. $fact_HTMLone = "code";

etc. etc.

Upvotes: 1

Views: 77

Answers (2)

Florian M&#252;ller
Florian M&#252;ller

Reputation: 7795

What you want to achieve is a replace of some strings. I'd suggest a solution like this:

<?php
$str_Facts = $row['facts'];
$replacements = array( "[start]" => "<tr><td class='FactsTableTDOne'><p>",
                       "[mid]"   => "</p></td><td class='FactsTableTDTwo'><p>",
                       "[end]"   => "</p></td></tr>" );
foreach ($replacements as $repkey => $repval) {
    $str_Facts = str_replace($repkey,$repval,$str_Facts);
}
echo $str_Facts;
?>

If you want to go on with your approach, you'd loop through the arrays (you have to ensure that the both arrays have the same number of elements).

<?php
$str_Facts = $row['facts'];
for ($i=0;$i<count($fact_BB);$i++) {
    //if you want to switch every uneven, do this:
    if ($i%2!=0) continue;
    $str_Facts = str_replace($fact_BB[$i],$fact_HTML[$i],$str_Facts);
}
echo $str_Facts;
?>

Upvotes: 0

Bfcm
Bfcm

Reputation: 2746

Sure. With $fact_HTML[0], $fact_HTML[1], $fact_HTML[n] etc. you can access your $fact_HTML array. Using modulo of 2 you can always access every 2nd (or first and second) elements of the array.

To check if the element is even or odd you can use:

if ($n % 2 == 0) {
   //even element
} else {
   //odd element
}

Also you can use Modulo 2 ($n % 2) as n to iterate through the array in the same way. You can also combine both variants.

$count = 10; //number of facts
for ($n = 0; $n < $count; $n++) {
    $fact_HTML[$n % 2] = $fact;
}

Upvotes: 1

Related Questions