I'm a little skeptical to answer your question because I think that the modulus operator is perhaps one of the most awesome little things in programming languages, but then again I have a degree in mathematics, so I'm probably a little biased on that regard.
Here's the basics:
When you divide a number by another number, sometimes you get what is called a remainder. e.g.,
8/2 = 4, no remainder -- but :
8/3 = 2, remainder 2 because 2*3 + 2 = 8.
Basically what the $number % 10
is checking is "what is the remainder of this number when I divide by 10?", and the answer, on the first go 'round for 123456 is 6, because 10 * 12345 + 6 = 123456. What happens in the while
loop is dividing the number by 10, so that 123456 becomes 12345.6, and the integer cast type sets $number
equal to 12345. It goes through the same operation-- what is the remainder of 12345 when I divide by 10? 5, because 1234 * 10 + 5 = 12345, and it adds that number to the running sum.
Although if I saw a student hand this in to me, I'd immediately know that something was up. Modulus operations can sometimes be difficult for anyone in coding who doesn't have a huge understanding of mathematics or a damn good understanding of coding, so for someone who is a beginner to pop up with an answer like this, I'm not sure I'd believe them.
Hopefully that answers your question on why the code works.
Edit
Here's what happens in your code, as you posted it, without using much of the PHP syntax:
- Set
$sum = 0;
and $number = 123456;
- Get the modulus of 123456 using 10, i.e. what is the remainder of 123456 when you divide by 10? 6.
- Sum the current value of
$sum
and the result of the modulus operation above. $sum
is currently set to 0, so 0+6 = 6. $sum
is now equal to 6.
- Set the value of
$number
to be the integer-only value of $number
's current value, divided by 10. Since $number
= 123456, 123456/10 - 12345.6, the integer portion of that is 12345, so $number = 12345
- Repeat steps 2-4 using the new value of
$number
set above.