【问题标题】:PHP modulus function not give me expected resultsPHP模数函数没有给我预期的结果
【发布时间】:2021-03-17 23:51:19
【问题描述】:

我正在尝试通过这个使用 WordPress 循环的简单示例来研究如何在 PHP 中使用模数函数我想在循环的每 1、2 和 3 次迭代中回显一条消息...

if ( $the_query->have_posts() ) {

    $counter = 0;

    while ( $the_query->have_posts() ) {

        $counter++;

        $the_query->the_post();

        if ($counter % 1 == 0) {
            
            $output .= '1 - ' . $counter . '<br />------------<br />';

        } elseif ($counter % 2 == 0) {

            $output .= '2 - ' . $counter . '<br />------------<br />';

        } elseif ($counter % 3 == 0) {

            $output .= '3 - ' . $counter . '<br />------------<br />';

        }

    }
   
}

虽然我在运行它时看到了这个..

1 – 1
————
1 – 2
————
1 – 3
————

谁能告诉我为什么我会看到这些结果?我期待看到 echo 1 2 和 3 在第一行和第二行输出。

【问题讨论】:

    标签: php modulus


    【解决方案1】:

    整数除以一没有余数!

    因此行

    if ($counter % 1 == 0)

    永远是真的!

    【讨论】:

      【解决方案2】:

      因为它总是满足第一个条件:

      // no matter what value is $counter , it always satisfy that the given value is always divisible by 1 and hence remainder will be 0 
      
      if ($counter % 1 == 0) {
                  
                  $output .= '1 - ' . $counter . '<br />------------<br />';
      ``
      That's why it don't go for other conditions
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多