Welcome Guest, Not a member yet? Register   Sign In
Accessing array keys as variables in view - acting weird.
#1

[eluser]illi[/eluser]
Hey!
I'm puzzled about one thing.

If I send this data to my view:
Code:
$data['country'] = 'UK';
$data['person'] = array('name'=>'John','hometown'=>'London');
//I'm only sending the person array to the view:
$this->load->view('main', $data['person']);
I can access the data like this in the view:
Code:
<?=$name?>
<?=$hometown?>
The thing is I can also access the country, even though I never passed it to the view:
Code:
<?=$country?>
<?=$name?>
<?=$hometown?>

Is this a feature or a bug? How is it possible?
#2

[eluser]InsiteFX[/eluser]
You should just be sending the $data array.

$this->load->view('main', $data);

InsiteFX
#3

[eluser]illi[/eluser]
Ok, can I ask why? All I need in that view is that particular array, and it's great to be able to access it with variables directly without having to use person['name'] in the view html.
#4

[eluser]mddd[/eluser]
Have you loaded $data['country'] to another view? The variables are shared between views. So if you have sent the country to another view before loading this view, $data['country'] will still be available.
#5

[eluser]$ilovephp[/eluser]
[quote author="mddd" date="1271939240"]Have you loaded $data['country'] to another view? The variables are shared between views. So if you have sent the country to another view before loading this view, $data['country'] will still be available.[/quote]

Really? this information is useful to me... thank you
#6

[eluser]illi[/eluser]
Yes, I'm sending $data around before $data['person'] is added, so that would be the case.

Great to know, thanks.
#7

[eluser]InsiteFX[/eluser]
You can also use this.

Code:
$this->load->vars($array);
$this->load->view('main');

echo $data['person']['name'];

InsiteFX
#8

[eluser]$ilovephp[/eluser]
[quote author="illi" date="1271953439"]Yes, I'm sending $data around before $data['person'] is added, so that would be the case.

Great to know, thanks.[/quote]

i recently tried this too.., but it isn't working . . .
#9

[eluser]InsiteFX[/eluser]
This function takes an associative array as input and generates variables using the PHP extract function. This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might want to use this function independently is if you would like to set some global variables in the constructor of your controller and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached and merged into one array for conversion to variables.

Code:
$this->load->vars($array)

InsiteFX




Theme © iAndrew 2016 - Forum software by © MyBB