A line of code speaks a gazillion words so:
$foo = false;
$bar = $foo ? $foo : 'bar';
/* $bar == 'bar' */
$foo = 'foo';
$bar = $foo ? $foo : 'bar';
/* $bar == 'foo' */
Is there a quicker way of saying "if something isn't false, then don't change it (if $foo
isn't false
then it stays as whatever it was, else, we'll change it)"?
Really: Thats really short! :D However, since 5.3 it gets even shorter
$bar = $foo ?: 'bar';
"Quicker" by what metric?
In terms of runtime, this will never be your bottleneck, so don't worry about it.
In terms of legibility, the following is clearly easier to read:
$foo = false; // done elsewhere
$bar = $foo;
if (!$bar) { // I've assumed from your examples that
// you meant more than just "not false"
$bar = 'bar';
}
$foo = false;
$bar = $foo ?: 'bar';
should return 'bar
$foo = true;
$bar = $foo ?: 'bar';
should return true;
AS of 5.3
My concern is that you could have a value that casts to false
$age = 0;
$myAge = $age ? $age : 21; //If no age assume drinking age
You wont get that with a direct, type sensitive comparison
if ($age ==== false) {
//stuff
}
Try to think not only of quicker writing but also of quicker reading.
Eventually you will learn that comfortable reading is way more important than these silly tricks in writing.
Not sure why that's always forgotten, but there is also a Perl-esque syntax:
$foo = $foo or $foo = "bar";
Or in your case just:
$foo or $foo = "bar";
I'm often using excessive spaces to keep it readable. Most importantly it really does no assignment unless $foo is false.