Question

i have a if statement, and i can write it in 2 ways:

1.  echo $danceInfo->getSearchingGigDes() ? $danceInfo : 'n/a';

or

2.  if ($danceInfo){ echo $danceInfo->getSearching(); }else{ echo 'n/a'; }

the first one doesnt seem to work, and i dont understand why ??!!

i've also tryed:

1.  echo $danceInfo->getSearchingGigDes() ? isset($danceInfo) : 'n/a';

but it doesn't work as well.

any ideas?

..i mean, i could use the 2'nd option but im curious on why it doesn't work.

thanks

Was it helpful?

Solution

The first one should be

echo $danceInfo ? $danceInfo->getSearchingGigDes() : 'n/a';

OTHER TIPS

Maybe you want

 echo (($danceInfo) ? $danceInfo->getSearching() : 'n/a');

First of all, how do the two different conditionals work? The construct

X1 ? Y1 : Z1;

is a condition written as an expression, where an expression is something that evaluates to a value, and which can be part of a larger expression. On the other hand,

if (X2 {
   Y2;
}
else {
   Z2;
}

is a statement, and is a complete "line of code" that does something (affects state, for example) and which cannot be embedded in a larger expression.

In both cases, the X1 and X2 are the conditions - sub-expressions that need to be evaluated to boolean values to decide which branch to take. PHP, in line with other major languages, allows a certain amount of implicit type conversion, so that if X1 and X2 do not evaluate to boolean values TRUE or FALSE, but instead to some other built-in type (such as strings or numbers), then their value is converted to boolean using well-defined rules. For example, a numeric zero is converted to FALSE and any non-zero value to TRUE. For strings, an empty string (or null) counts as FALSE, while anything else is seen as TRUE.

In your code above, the condition sub-expressions on the two conditionals are completely different, so you should not expect them to produce the same results. In the first, the condition is the result of echo'ing a string to the output - so the boolean value that decides which branch to take will be converted from the return value of 'echo'. echo (http://php.net/manual/en/function.echo.php) has void return type, so I think it should always evaluate to false. In the second conditional, you use the value of $displayInfo - if this is non-null, non-zero or non empty string, this will evaluate to TRUE, and you will see the outut of the echo expression, otherwise you will see 'n/a' on the output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top