Skip to content
loading...

re: Best Practice - Check if property exist and assign VIEW POST

FULL DISCUSSION
 

And at some point I came up with inline if's which makes it easier to write/read and maintain.

AKA Ternary statements.

I point this out because it's helpful to know and use the name, and googling "? :" doesn't work out too well. I remember trying to do so years ago when I wanted to know wtf these were called so that I could really understand what all I could do with them. :)

Also, while they may be less to write, it could be argued (successfully I think) that ternaries are more difficult to read than if/elseif/else statements with brackets. Though for small things, as in your example here, they probably do make more sense than an if/else block for every property.

If you find yourself doing things like this though, almost definitely reach for the if/elseif/else blocks because while valid, this gets ugly fast...

for ($i = 1; $i <= 100; $i++) {
    $mod3 = $i % 3;
    $mod5 = $i % 5;
    echo (!$mod3 && !$mod5 ? "FizzBuzz" : (!$mod3 ? "Fizz" : (!$mod5 ? "Buzz" : $i))) ."\n";
}

:D

code of conduct - report abuse