Arvind Ravi Arvind Ravi - 24 days ago 8
PHP Question

Passing multiple variables to a view?

so,i have two variables

$posts
and
$comments
that holds the array of posts and comments respectively,i have a separate view that accepts these variables,executes a foreach loop and prints them on the same page. The question here is,how do i pass both the variables to a view?

If its a single variable i pass it like this
$this->load->view('myview',$myvar)
.

I tried passing it as an array like this,but still it doesnt work.

$data=array($var1,$var2);
$this->load->view('myview',$data);


Any help would be greatly appreciated! Thanks.

Answer

You need to access the variable in your view as you pass it. Using array($var1,$var2); is valid but probably not what you wanted to achieve.

Try

$data = $var1 + $var2;

or

$data = array_merge($var1, $var2);

instead. See Views for detailed documentation how to access variables passed to a view.

The problem with using array($var1,$var2); is that you will create two view variables: ${0} and ${1} (the array's keys become the variable names, you have two keys in your array: 0 and 1).

Those variable names are invalid labels so you need to enclose the name with {} on the view level.

By that you loose the ability to name the variables usefully.