4

I am passing variable to my index view in Yii2 framework. I have the following code:

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

I only need to pass variable $userresult if user is logged in since if user is not logged in, the $userresult variable does not exist. This is what I tried but I can not get the if statement to run:

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

How can this be achieved?

1 Answer 1

3

One of the ways to do it:

// 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 echo with array is obviously wrong. You should learn more about arrays in plain PHP.

Also you can forget about array() syntax, use shorter variation [] since Yii2 requires PHP >= 5.4.

And I think it's better to pass null instead:

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

Then you check if the variable is null or not, or just if ($userresult) { ... } in view. I think it's better then using isset in view. That way params number is constant.

Sign up to request clarification or add additional context in comments.

3 Comments

Does this code go to my config or my current script?
In your current script. Also see suggested alternative.
Ok, I just tried it on my current script and it worked. You sir is a boss! Thanks for your help once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.