tags:

views:

87

answers:

5

can someone please explain PHP's operator % in full detail? with examples would be nice!

+7  A: 

It's the modulus operator, which gives the integer remainder of a division e.g.

7 / 2 = 3.5  // 3 remainder 1
7 % 2 = 1    // the remainder

Obvious real world example is working out whether a number is odd or even

if (($n % 2) == 0) the number is even, else it's odd... useful when you want to show alternate rows in a table in different colours

Mark Baker
It's not the fractional part of the division, it's the remainder, so `7 % 2` is `1`, not `.5`
Michael Mrozek
Your second example should be 7 % 2 = 1 because 7 / 2 = 3 with remainder 1.
murgatroid99
Yup, you guys caught me mid-edit after my cut and paste
Mark Baker
+1  A: 

% is used for remainder

Example :-Print if number is even or odd?

  (@num % 2 == 0 )? 'even' : 'odd'
Salil
A: 

It's the modulus operator. It gives you the "remainder" after a division. It's a fairly standard operator.

Here is the PHP reference for Arithmetic Operators.

rtalbot
+1  A: 

% is modulus operator an example

$num1 = 160;
$num2 = 15;
$result = $num1 % $num2;
echo "The modulus of these numbers is $result";
Osman Üngür
A: 

It will give you the modulo, or "mod", of two numbers, which is the remainder when you divide two numbers. It's a common arithmetic operator, and I can't think of a language that doesn't have it. More info at http://en.wikipedia.org/wiki/Modulo_operator.

There are two ways that you can use it. The most common is like any other arithmetic operator:

$bwah = 3 % 1; // == 0
$bwah = 10 % 3; // == 1

There is also a short hand way of doing it, just like +=, -=, *=, and /=

$bwah = 10;
$bwah %= 3; // == 1 ... it's like saying 10 % 3
Sam Bisbee