What is %2 in $id%2
What does %2 do in the following php?
$id=(开发者_如何学Cint)@$_REQUEST['id'];
echo ( !($id%2) )?
"{'id':$id,'success':1}":
"{'id':$id,'success':0,'error':'Could not delete subscriber'}";
%
is the modulus operator. % 2
is therefore the remainder after division by two, so either 0 (in case $id
was even) or 1 (in case $id
was odd).
The expression !($id % 2)
uses automatic conversion to a boolean value (in which 0 represents false and everything non-zero represents true) and negates the result. So the result of that expression is true if $id
was even and false
if it was odd. That also determines what the echo
prints there. Apparently an even value for $id
signals success.
A slightly more elaborate but maybe easier to understand way to write above statement would be:
if ($id % 2 == 0)
echo "{'id':$id,'success':1}";
else
echo "{'id':$id,'success':0,'error':'Could not delete subscriber'}";
But that spoils all the fun with the ternary operator. Still, I'd have written the condition not as !($id%2)
but rather as ($id % 2 != 0)
. Mis-using integers for boolean values leads to some hard to diagnose errors sometimes :-)
%
is the modulo operator. So $id % 2
will return 0
if the value of $id
is even and 1
if the value is odd.
This is checking if the ID is even. If it's even, then PHP will evaluate that 0 as false.
Check out the Modulus section for PHP, Basically if it's Modulus 2 the Success else error
As the others said, %
will give you the remainder after dividing by that number. In effect this code block will echo "success = 1" if the id is even (or not a number, or not defined(!!)), and "success = 0" if the id is odd.
精彩评论