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

前端 未结 9 2612
[愿得一人]
[愿得一人] 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 02:50
          <?php
    
    for ($i = 1; $i <= 100; $i++) {
    
        if ($i % 15 == 0) echo "This Number is Divisible by 3 and 5<br>";
        else if ($i % 3 == 0) echo "This Number is Divisible by 3 only<br>";
        else if ($i % 5 == 0) echo "This number is Divisible by 5 only<br>";
        else{
            echo "$i<br>";
        }
    
    }
    
       ?>
    
    0 讨论(0)
  • 2021-02-19 02:54
    <?php
    
    if($number % 5 == 0 && $number % 3 == 0)  {
        echo "BY3 AND 5";
    } elseif ($number % 5 == 0) {
        echo "BY5";
    } elseif ($number % 3 == 0) {
        echo "BY3";
    } else{
        echo "NOT BY3 OR 5";
    }   
    ?>
    
    0 讨论(0)
  • 2021-02-19 02:55

    This is neater and completed to be run:

    <?php
    
    for ($i = 1; $i <= 100; $i++) { 
                    if ($i % 15 == 0)
                    {
                        echo"Divisible by 3 and 5</br>";
                    }
                    elseif ($i%3==0)
                    {
                        echo"Divisible by 3</br>";
                    }
                    elseif ($i%5==0)
                    {
                        echo"Divisible by 5</br>";
                    }
                    else
                    {
                        echo $i,"</br>";
                    }
    
    }
    ?>
    
    0 讨论(0)
  • 2021-02-19 02:59
    $num_count = 100;
        $div_3 = "Divisible by 3";
        $div_5 = "Divisible by 5";
        $div_both = "Divisible by 3 and 5";
        $not_div = "Not Divisible by 3 or 5";
    
        for($i=0;$i<=$num_count;$i++)
        {
            switch($i)
            {
                case ($i%15==0):
                echo $i." (".$div_both.")</br>";
                break;
                case ($i%3==0):
                echo $i." (".$div_3.")</br>";
                break;
                case ($i%5==0):
                echo $i." (".$div_5.")</br>";
                break;
                default:
                echo $i."</br>";
                break;
            }
        }
    
    0 讨论(0)
  • 2021-02-19 02:59

    No need to do three if statements:

    echo "<table border='1'>";
    
    for ($i = 1; $i <= 100; $i++) {
    
        echo "<tr><td>{$i}</td><td>";
    
        if ($i % 3 == 0) echo "BY3 ";
        if ($i % 5 == 0) echo "BY5";
    
        echo "</td></tr>\n";
    }
    echo "</table>";
    
    0 讨论(0)
  • 2021-02-19 02:59
    if($number % 15 == 0)  
    {
         echo "Divisible by 3 and 5";
    } 
    elseif ($number % 5 == 0) 
    {
        echo "Divisible by 5";
    } 
    elseif ($number % 3 == 0) 
    {
     echo "Divisible by 3";
    }
    
    0 讨论(0)
提交回复
热议问题