What does %2 do in the following php?
$id=(int)@$_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 :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With