Skip to content
Advertisement

How to replace every time a number appears within range?

I’ve been looking high and low for this, but I can’t seem to find the best way to do this?

I want to basically run through a simple range of numbers 1-20, and every time there is a “3” listed, like 3 or 13, replace that with a value like “thisisa3value”

I’m just a little stumped on the best way that can be done?

This is the code I have so far but it doesn’t seem to be working, as it basically prints this out on each number. I want it to basically just ONLY do that for ones that have a 3 associated with it. Can someone please take a look and let me know what I’m doing wrong?

<?php
foreach (range(1, 20) as $number ) {
echo $number;
echo '&nbsp;';
if ( in_array(3, range(1,20)) ) {
echo '   thisisa3value ';
}
}
?>

To reiterate, I just want it to basically print out like this:

1, 2, this is a 3 value, 4, 5, 6, 7, 8, 9, 10, 11, 12, this is a 3 value, 14, 15, 16, 17, 18, 29, 20.

Any help would be greatly appreciated. Thanks!

Advertisement

Answer

This Code may help you

foreach (range(1, 20) as $number ) {
    echo $number;
    echo '<br>';
    if (strstr($number, '3')) {
           echo '   thisisa3value <br>';
    }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement