计算范围内回声多少次?

问题描述

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

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

但我希望它显示出类似的数字

foo:列出6次 酒吧:列出4次

有人知道回声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