If you need to check if there is any value in the array, and if not, set the default value for the variable, you will do something like this
$authToken = isset($response['fbData']['authResponse']['accessToken']) ? $response['fbData']['authResponse']['accessToken'] : null;
I wonder if there is a way to make this somehow more readable?
There is a short version of the ternary operator
$authToken = $sourceVar ?: null;
There is no need to repeat the source code here a second time, but it does not work with arrays, because if I use $response['fbData']['authResponse']['accessToken']instead $sourceVar, I will get a 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 still don't like it.
I could use something like this
$a = isset($response['fbData']['authResponse']['accessToken']) ?: null;
But in this case, I will get TRUE as the result, the result isset().
So maybe someone knows how to do it right?
1: PHP? , " PHP" . . , PHP, ( - $response['fbData']['authResponse']['accessToken'] , ).
2: , NikiC (. ).
: Php , , - :
function myIsset (&$var, $defaultVal = null) {
return isset($var) ? $var : $defaultVal;
}
$authToken = myIsset($response['fbData']['authResponse']['accessToken']);
UPD2 10/27/2015: PHP 7 ?? ( ), : , NULL; .
$authToken = $response['fbData']['authResponse']['accessToken'] ?? 'any_default_value';
- php notice!
, , :
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';