计算某物在一个范围内回显了多少次?

Count how many times something was echoed in a range?

我只是有点难过,我列出了一个简单的1-20范围,并显示如下,显示一个范围内的3的倍数,以及一个范围内的5的倍数。这些显示有回声,有没有可能我可以计算特定倍数 displayed/echoed 的次数?例如,这就是我所拥有的:

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

但我希望它显示像

这样的计数

foo: 列出6次 bar: 4次上市

有谁知道可以使用 echo substr_count 来处理在 1-20 范围内回显的词“foo”和“bar”吗?

让我知道是否可以澄清。任何指导将不胜感激!

这是我的代码:

<?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>";
?>

使用输出缓冲函数将回显输出捕获到变量中。

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>";

但是这样做很傻,你可以在循环中递增计数器:

$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