Is there a way to do the following, but in short if/then syntax:
if($method->isAbstract()) {
$details['abstract'] = true;
}
If I do:
$details['abstract'] = $method->isAbstract() ? true : null;
It is not quite the same, because the array key abstract
is always set. I only way the array key set if isAbstract()
is true. To clarify, if isAbstract() is false, don't set the key in the array.
Thanks.
I don't have a PHP interpreter at hand, but I guess this will work:
$method->isAbstract() && $details['abstract'] = true;
Update: yes, it works → http://codepad.org/lW23FR0j
I wouldn't worry too much about trying to shorten three lines of code, which in all honesty could be written in one line anyway:
if ( $obj->method() ) $data['key'] = 'value' ;
However, as @Mischa's answer demonstrated, there are shorter ways. You could use the logical operator &&
to perform assignment as well:
$obj->method() && $data['key'] = 'value' ;
In this method, the expression on the right is evaluated if the expression on the left is "true".
Another method is the new shorter ternary operator which excludes the second expression. While you presented the long-form ternary as an alternative in your original question, you could also consider the new format provided since PHP 5.3
!$obj->method() ?: $data['key'] = 'value' ;
Since we're not using the second expression, we invert our test in the first expression. No longer checking for a positive, we are now looking for a negative. When the negative is found, our assignment takes place.
I don't provide this answer to encourage you to avoid 3-line solutions, but only to encourage you to feel free to explore shorter solutions from time to time as they often times lead to parts of the language you may not have otherwise discovered.