What is% 2 in $ id% 2

What does% 2 do in the next php?

$id=(int)@$_REQUEST['id']; echo ( !($id%2) )? "{'id':$id,'success':1}": "{'id':$id,'success':0,'error':'Could not delete subscriber'}"; 
+4
source share
5 answers

% is an operator module . Thus, % 2 is the remainder after dividing by two, therefore either 0 (in the case if $id was even) or 1 (in the case of $id was odd).

The expression !($id % 2) uses automatic conversion to a boolean value (in which 0 represents false and all non-zero represents true) and negates the result. Thus, the result of this expression is true if $id was even and false if it was odd. It also determines what echo prints there. Apparently an even value for $id means success.

Somewhat more complicated, but perhaps easier to understand, is how to write the above statement:

 if ($id % 2 == 0) echo "{'id':$id,'success':1}"; else echo "{'id':$id,'success':0,'error':'Could not delete subscriber'}"; 

But it spoils all the pleasures with the help of the ternary operator. However, I would not write the condition as !($id%2) , but rather as ($id % 2 != 0) . Bad integers for Boolean values ​​sometimes make it difficult to diagnose errors :-)

+16
source

% is a modulo operator. So $id % 2 will return 0 if the value of $id is equal to 1 if the value is odd.

+2
source

This checks if the identifier is even. Even if it is, then PHP will evaluate this value 0 as false.

0
source

Check the "Modules" section for PHP, in principle, if it is module 2 else success error

0
source

As others have said, % will give you the remainder after dividing by this number. In essence, this code block will echo "success = 1" if id is even (or not a number or not defined (!!)), and "success = 0" if the identifier is odd.

0
source

All Articles