Using numeric indices to pass data from controller to view
Question by raheel shan
I have a simple question. Let me explain
We use this to pass data from controller to view
function index(){
$data['title'] = 'This is title';
$data['message'] = 'This is message';
$this->load->view('test',$data);
}
Here we are using Associative Array to pass data
And now this function again and use indexed array instead of Associative Array
function index(){
$data[] = 'This is title';
$data[] = 'This is message';
$this->load->view('test',$data);
}
And now in View this does not work.
echo $data[0];
echo '<br>';
echo $data[1];
i only want to know if why this does not work. And in the user guide i never read that associative array is necessary.
Answer by Starx
The view data are converted into variables when parsed. A similar result of what extract()
function of PHP gives. For example:
$data['title'] = 'This is the title';
will be accessible directly as $title
not $data['title']
. In fact, if you look at the sources, you will find it does uses extract()
and similar conversion happens on your case to, but since variable $0
and $1
are invalid so they are not available.
Stick to string indexing. If that is not an option, then you might want to prefix something before the texts like:
$data['d0'] = 'This is the title';
Read the manual here its quoted. However, you can pass an array instead of a string and giving the exact result of what you want.
$data['data'] = array('This is the title', 'This is the description');
Now, this you will be access using $data[0]
and $data[1]
.