Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is %2 in $id%2

Tags:

syntax

php

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'}";
like image 571
shin Avatar asked Dec 01 '22 06:12

shin


1 Answers

% 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 :-)

like image 155
Joey Avatar answered Dec 04 '22 03:12

Joey