0
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?

7
  • 12/8=1, 12%8=4 This is the modulo operation which gives you the remainder after division. Commented Aug 3, 2017 at 2:38
  • i do understand that. But what this : define ("num", "12") really meant? is it num is holding a value of 12? so when echo num%8 is actually 12%8? Commented Aug 3, 2017 at 2:42
  • Why don't you read the manual? On the page there are examples that show exactly this. Commented Aug 3, 2017 at 2:44
  • It really helps! Now I understand. Thanks! Commented Aug 3, 2017 at 2:47
  • Okay, I've moved that to an answer. Commented Aug 3, 2017 at 2:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation! I do understand now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.