Reputation: 3680
I'm trying to work out if one string, $a, is divisible by another, $b.
All of the examples I can find tell me to use modulus, e.g.:
if(($a %$b) == 0) : echo "Is dividible" ; endif;
However, because modulus returns the remainder of the calculation, this doesn't work if $b is larger than $a, because there's still no remainder.
How do I check divisibility where $b is sometimes (but not always) larger than $a?
Upvotes: 0
Views: 146
Reputation: 457
Try this it should work:
$a = 7;
$b = 14;
//echo ( ($a > $b) && ( ($a % $b) == 0) ) ? "is divisible":"no divisible";
echo ( ($a < $b) && (($b % $a) == 0) ) ? "Is dividible" : "Is not divisable" ;
Upvotes: 0
Reputation: 6354
why don't you do this as a function:
function isDivisible($smaller,$bigger){
//handle division by zero, and hmm.. let's cover negative numbers too
if($smaller<=0) return false;
if($smaller>$bigger) return false;
return !($bigger % $smaller);
}
The negation !
should be a working and elegant way to handle it.
Upvotes: 2
Reputation: 4038
if($a==$b)
{echo "divisible a and b are equal";
}
else if($a>$b){
if(($a %$b) == 0) : echo "Is dividible" ; endif;
}
else{
echo "\$b is either large or equal to \$a";
}
Upvotes: 0
Reputation: 201
How about:
echo ( ($a < $b) && (($a % $b) == 0) ) ? "Is dividible" : "Is not divisable" ;
Upvotes: 1
Reputation: 735
You can use ternary operator as example given below
(($a%$b)==0)?echo "Is divisible": echo "not divisible";
Upvotes: -1