user391986
user391986

Reputation: 30896

php framework, data works in var_dump but not in echo

I am so confused right now, I am using code igniter php framework and have passed an array to the view so I can access the variable from within the view.

So in this view when I do

echo var_dump($data["mykey"]);

I get

string '43' (length=2)

but when I try

echo $data["mykey"];

I get

A PHP Error was encountered
Severity: Notice
Message: Undefined index: "mykey"
Line Number: 8

???

EDIT (problem seems to be when code igniter tries to return from the view to pass it back to the controller as a string, this is my conclusion because if I put a die at the end of the view it works)

The $data array is like so and in my view I try to do echo $data["myfield"][0]["data"]

array
  'myfield' => 
    array
      0 => 
        array
          'data' => string '1'
  'myfieldb' => 
    array
      0 => 
        array
          'data' => string '2'

Upvotes: 3

Views: 1590

Answers (2)

afarazit
afarazit

Reputation: 4984

in your controller

class controller extends CI_Controller {

function hello() {
  $data['world'] = 'world';
  $this->load->view('test');
 }
}

in your view

<html>
<head></head>
<body>
Hello <?php echo $world ?>;
</body>
</html>

Array keys passed to views are converted to variables.

So to access $data['mykey'] in your view you must access it like $mykey instead of $data['mykey'].

<html>
<head></head>
<body>
Your key is: <?php echo $mykey ?>;
</body>
</html>

Here's the user_guide

Upvotes: 3

Steve Robbins
Steve Robbins

Reputation: 13812

When I recreate what you've given in PHP

<?php

    $array = array(
              'myfield' => 
                array(
                  0 => 
                    array(
                      'data' => '1')),
              'myfieldb' => 
                array(
                  0 => 
                    array(
                      'data' => '2')));

    echo $array['myfield'][0]['data'];

?>

It echo's fine.

That error you're getting means that the key specified doesn't exist. I would do a print_r($data) and see what you get.

Upvotes: 0

Related Questions