define ("num", "12");
echo num%8;
From what I found from google, define() hold a constant value and the value is num and 12. So my confusion is how come when echo num%8 is equal to 4? Can somebody explain this?
The define function defines a variable at runtime, as the name suggests. So define("num", "12") just defines the variable named num with contents "12".
From the manual:
define — Defines a named constant
After that you have num % 8 which essentially evaluates to 12 % 8. At this point PHP converts your String value into an Integer value because you demand the % operator which operates on numbers. Therefore see echo "12" % 8 which also outputs 4.
As a small experiment, take a look at this:
define("num", "12");
echo gettype(num); // Outputs: string
echo gettype(num + 1); // Outputs: integer
So as you see PHP automatically converts the type if you demand it.
Last note that % is the modulo operator. It divides the number to the left by the number to the right and returns the remainder.
So 12 / 8 is 1 and a remainder of 4. That is why it outputs 4.
12/8=1, 12%8=4This is themodulo operationwhich gives you the remainder after division.