When you need to check is there any value in array, and if not - set default value for variable, you do something like this
$authToken = isset($response['fbData']['authResponse']['accessToken']) ? $response['fbData']['authResponse']['accessToken'] : null;
I wonder, is there any way to do it somehow more readable?
There is short version of ternary operator
$authToken = $sourceVar ?: null;
No need to repeat source here second time, but it doesn't work with arrays, because if I will use $response['fbData']['authResponse']['accessToken']
instead of $sourceVar
- I will get php warning message.
I can use @
$authToken = @$response['fbData']['authResponse']['accessToken'] ?: null;
I heard that they made "@" really fast in PHP 5.4
, but I don't like this anyway.
I could use something like this
$a = isset($response['fbData']['authResponse']['accessToken']) ?: null;
But in this case I will get TRUE as result, result of isset()
.
So, maybe somebody knows, how to do it right?
Upd1: Suggested topic How can I create a new operator in PHP? is not answers my question because there user asks "how to change PHP" and create a new operator. I do not need this. There are some answers how to do similar things without PHP modifications but they are do not work for arrays (I can't pass something like this $response['fbData']['authResponse']['accessToken']
in function because it will generate warning message).
Upd2: Problem solved, thanks to NikiC (see comment below). The idea: Php wont generate warning message if I will pass array element as a link, so it gives us a chance to use something like this:
function myIsset (&$var, $defaultVal = null) {
return isset($var) ? $var : $defaultVal;
}
$authToken = myIsset($response['fbData']['authResponse']['accessToken']);
UPD2 10/27/2015: PHP 7 has new awesome operator ??
(The null coalesce operator) that solved this problem completely and is the best way to do it: It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
$authToken = $response['fbData']['authResponse']['accessToken'] ?? 'any_default_value';
And if requested array key does not exits - it does not generate php notice
!
You can use it also like this, looking for not empty value:
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';