In PHP, I wanted to do something like $myArray->get('key', 'default')
, but that doesn't work in PHP for a number of reasons. (Namely,
arrays aren't objects and there isn't a get()
function for arrays.) I found it worked with @$myArray['key'] || false
, but only
because I was using a Boolean value, like false
. The ||
operator always causes the interpreter to treat expressions on each side of
it as Booleans. If I tried a different default value, like @$myArray['key'] || 'default'
, it didn't work as I expected, because it
treats 'default'
as a Boolean true
.
However, since version 5.3, PHP's ternary operator allows an empty "then" result, which returns the initial condition if it's true,
otherwise, it returns the required "else" result. The following code illustrates the difference between using ||
and ?:
.
Update: I've noticed that if the initial value used with ?:
is an empty, non-null string (i.e. ''
), this breaks down. It's being converted to a Boolean false, apparently.