Skip to content
Advertisement

Count how many times something was echoed in a range?

I’m just a little stumped, I have a simple range of 1-20 listed out, and displays as follows, showing multiples of 3 within a range, and multiples of 5 within a range. These were displayed with echoes, is there a possible way that I can just count the number of times a specific multiple was displayed/echoed? for instance this is what I have:

1, 2, 3foo, 4, 5bar, 6foo, 7, 8, 9foo, 10bar, 11, 12foo, 13, 14, 15bar, 16, 17, 18foo, 19, 20bar

but I would like it to show a count like

foo: 6 times listed bar: 4 times listed

Does anyone know of a possible way to use echo substr_count for just words “foo” and “bar” that have been echoed within a range of 1-20?

Let me know if I can clarify. Any guidance would be greatly appreciated!

This is my code:

<?php
foreach (range(1, 20) as $number ) {
echo $number;
echo '&nbsp;';

if ($number % 3 == 0 && $number %5 == 0) {
echo "foobar ";

} elseif ($number % 3 == 0)  {
echo "foo ";

} elseif ($number % 5 == 0) {
echo "bar ";
}

}
echo "<br>";
ob_start();
// code that prints all the numbers
$output = ob_get_flush();
$foo_count = substr_count($output, "foo");
$bar_count = substr_count($output, "bar");

echo "foo: $foo_count times listed<br>";
echo "bar: $bar_count times listed<br>";
?>

Advertisement

Answer

Use the output buffering functions to capture echoed output into a variable.

ob_start();

foreach (range(1, 20) as $number ) {
    echo $number;
    echo '&nbsp;';

    if ($number % 3 == 0 && $number %5 == 0) {
        echo "foobar ";

    } elseif ($number % 3 == 0)  {
        echo "foo ";

    } elseif ($number % 5 == 0) {
        echo "bar ";
    }
}

$output = ob_get_flush();
$foo_count = substr_count($output, "foo");
$bar_count = substr_count($output, "bar");

echo "foo: $foo_count times listed<br>";
echo "bar: $bar_count times listed<br>";

But doing it this way is silly, you can just increment the counters in the loop:

$foo_count = $bar_count = 0;
foreach (range(1, 20) as $number ) {
    echo $number;
    echo '&nbsp;';

    if ($number % 3 == 0 && $number %5 == 0) {
        echo "foobar ";
        $foo_count++;
        $bar_count++;

    } elseif ($number % 3 == 0)  {
        echo "foo ";
        $foo_count++;

    } elseif ($number % 5 == 0) {
        echo "bar ";
        $bar_count++;
    }
}

DEMO

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement