November 1, 2012

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';

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';

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].

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!