2

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)"?

Jonathon Oates
  • 2,912
  • 3
  • 37
  • 60

6 Answers6

10

Really: Thats really short! :D However, since 5.3 it gets even shorter

$bar = $foo ?: 'bar';
KingCrunch
  • 128,817
  • 21
  • 151
  • 173
7

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
2
$foo = false;
$bar = $foo ?: 'bar';

should return 'bar

$foo = true;
$bar = $foo ?: 'bar';

should return true;

AS of 5.3

Ian Wood
  • 6,515
  • 5
  • 34
  • 73
1

"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';
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

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
}
preinheimer
  • 3,712
  • 20
  • 34
0

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • It is indeed better than the full ternary operator, and it's not just quicker, but shorter too: `$x = expensive_function() ? expensive_function() : 1;` ==> `$x = expensive_function() or $x = 1;` – biziclop Sep 07 '13 at 17:03
  • @biziclop Maybe you meant `$x = expensive_function() ?: 1`? Because your solution always returns a boolean, which may be not wanted. – KingCrunch Oct 27 '13 at 03:08