$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"' : '';
Can anyone explain to me what that question mark does in this line of code? Thanks a lot!
This is called the Ternary Operator, and it's common to several languages, including PHP, Javascript, Python, Ruby...
$x = $condition ? $trueVal : $falseVal; // same as: if ($condition) { $x = $trueVal; } else { $x = $falseVal; }
One very important point to note, when using a ternary in PHP is this:
Note: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions. source
Actually this statment is representing a Ternary operation, a conditional expression:
// works like: (condition) ? if-true : if-false; $hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? 'style="display:none;"':'';
in your case $hideCode
will have style="display:none;"
value if
$likesObj->isAlreadyLikedByUser(facebookUID())
will return true, else it will be null or empty.
It's a shorter version of a IF statement.
$hideCode = $likesObj->isAlreadyLikedByUser(facebookUID()) ? ' style="display:none;"':'';
if in fact :
if($likesObj->isAlreadyLikedByUser(facebookUID()))
{
$hideCode = 'style="display:none"';
}
else
{
$hideCode = "";
}
For the purism :
It's representing a Ternary operation
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