Add a variable to an array only if it matters in PHP?

I am transferring the variable to my indexview in the Yii2 structure. I have the following code:

return $this->render('index', array(
    'userresult' => $userresult,
    'topresult' => $topresult,
    'result' => $result
));

I need to pass the variable $userresultif the user is logged in, because if the user is not logged in, the variable $userresultdoes not exist. This is what I tried, but I cannot get the statement ifto run:

return $this->render('index', array(
    if (!\Yii::$app->user->isGuest) { echo "'userresult' => $userresult"; },
    'topresult' => $topresult,
    'result' => $result
));

How can this be achieved?

+4
source share
1 answer

One way to do this:

// Initial array
$params = [
    'topresult' => $topresult,
    'result' => $result,
];

// Conditionally add other elements to array
if (!\Yii::$app->user->isGuest) {
    $params['userresult'] = $userresult
}

return $this->render('index', $params);

Mixing echowith an array is obviously wrong. You should learn more about arrays in simple PHP.

array(), [], Yii2 PHP >= 5.4.

, null :

return $this->render('index', [
    'userresult' => $userresult ?: null,
    'topresult' => $topresult,
    'result' => $result
]);

, null , if ($userresult) { ... }. , , isset. , .

+3

All Articles