Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP question mark

Tags:

php

$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!

like image 788
user829814 Avatar asked Jul 05 '11 13:07

user829814


3 Answers

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

like image 172
nickf Avatar answered Sep 22 '22 02:09

nickf


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.

like image 35
Ovais Khatri Avatar answered Sep 26 '22 02:09

Ovais Khatri


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

like image 27
Patrick Desjardins Avatar answered Sep 22 '22 02:09

Patrick Desjardins