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. If not by any then show nothing.
This is what I've got so far, but any help would be great since not sure about the / by 3 and 5 bit as you can see below.
<?php $var = range(0, 100); ?>
<table>
<?php foreach ($var as &$number) {
echo " <tr>
<td>$number</td>
<td>";
if($number % 3 == 0) {
echo "BY3";
} elseif ($number % 5 == 0) {
echo "BY5";
} elseif ($number % 3 and 5 == 0) {
echo "BY3 AND 5";
}
echo "</td></tr>";
}
?>
</table>
Thanks
Method: This can also be done by checking if the number is divisible by 15, since the LCM of 3 and 5 is 15 and any number divisible by 15 is divisible by 3 and 5 and vice versa also.
To check if a number is divisible by another number, we can use the % modulo operator in PHP. The modulo % operator returns the remainder of two numbers 20 % 5 = 0 , so if we get a remainder 0 then the given number is a divisible of another number otherwise it not a divisible.
PHP | bcdiv() Function The bcdiv() function in PHP is an inbuilt function and is used to divide two arbitrary precision numbers. This function accepts two arbitrary precision numbers as strings and returns the division of the two numbers after scaling the result to a specified precision.
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
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" : ""));
$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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With