Could someone please help me with the above operator.
I am trying to find out what exactly it does and how it works but to no avail could someone explain it for me please possibly with an example
Cheers
Could someone please help me with the above operator.
I am trying to find out what exactly it does and how it works but to no avail could someone explain it for me please possibly with an example
Cheers
It returns the remainder after a division. So:
4%2 = 0 (since 4/2 = 2 with no remainder)
3%2 = 5 (since 3/2 = 1.5)
Many times this is used in figuring out alternating row colors. A counter starts at 1, then increments on each loop through a while() or for() or foreach() loop. On each itteration, the modulus operator is used to see if it's an "odd" row (i.e. divisible by 2 or not). Something like:
$i=1;
while($row = mysql_fetch_assoc($result))
{
// Do we need a specific BG color?
if($i%2 != 0)
$bgcolor = '#fff';
else
$bgcolor = '#abd';
// Do something with the database result
$i++;
}
However, that's not its only use. I'm sure there are thousands of ways you can use the operator. But as it states in the manual, it will return the remainder of a division operation (like above).
The modulus is the remainder of one number divided by the other.
<?php
$a = 5;
$b = 2;
$c = $a % $b;
echo $c;
?>
=1
So will the result always be a 1 or a 0???
No, it will be the remainder of that division. So is 25/4 a remainder of 1? It's 6.2xxx so the remainder is 2.
Or, you could try and find out Always much better that way.
I was trying it out that is what led me to the question.
$a = 24;
$b = 4;
$c = $a % $b;
echo $c;
my output is 0.
I think this is what is confusing me
because 24 is divisible by 4... 24/4 = 6.0
try 30 and 4: 30/4 = 7.5
I think I might finally of got it. I am a bit slow i know.
Its whatever is left after a division
31%4 = 3 (4 into 31 goes 7 times and 3 left over)
so 18%5 is 5 into 18 goes 3 times and 3 left over.
Cheers guys
don't forget to mark this as resolved.