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.
<?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>";
}
}
?>
<?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";
}
?>
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>";
}
}
?>
$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;
}
}
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>";
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";
}