PHP - If number is divisible by 3 and 5 then echo

前端 未结 9 2646
[愿得一人]
[愿得一人] 2021-02-19 02:13

I\'m new to PHP and trying to create the following whilst minimizing the amount of code needed. PHP should show a list of 100 then display if the number is / by 3, 5 or 3 and 5.

相关标签:
9条回答
  • 2021-02-19 03:08

    Nope... you should check first if it's divisble for 15 (3x5) (or 3 and 5) and after you can do other checks:

    if($number % 15 == 0)  {
        echo "BY3 AND 5";
    } elseif ($number % 5 == 0) {
        echo "BY5";
    } elseif ($number % 3 == 0) {
        echo "BY3";
    }
     echo "</td></tr>";
    
    ?>
    

    Because every number divisble for 15 is also divisble for 3 and 5. So your last check could never hit

    0 讨论(0)
  • 2021-02-19 03:08

    Update the code as given below

    <?php $var = range(0, 100); ?>
    <table>
    <?php foreach ($var as &$number)
    {
    echo " <tr>
    <td>$number</td>
    <td>";
    
    if($number % 3 == 0 &&  $number % 5 == 0) 
    {
       echo "BY3 AND 5";
    } 
    elseif ($number % 5 == 0) 
    {
    echo "BY5";
    }
    elseif ($number % 3 == 0) 
    {
        echo "BY3";
    }
    echo "</td></tr>";
    }
    ?>
    

    0 讨论(0)
  • 2021-02-19 03:16

    if I'm reading your question correct then you are looking for :

    if ($number % 3 == 0 && $number %5 == 0) {
            echo "BY3 AND 5";
    } elseif ($number % 3 == 0)  {
        echo "BY3";
    } elseif ($number % 5 == 0) {
        echo "BY5";
    }
    

    Alternative version :

    echo ($number % 3 ? ($number % 5 ? "BY3 and 5" : "BY 3") : ($number % 5 ? "BY 5" : ""));
    
    0 讨论(0)
提交回复
热议问题