0

I am trying to print selected product names from my database, however all i see is the word "Array" instead of the product name. It is displayed as many times as the number products it finds, and that number is correct, but it only shows "Array"...

Here's my code:

public function lookup($product)
    {

        $camera = $this->db->query("SELECT name FROM products WHERE type = 'Camera' ");

        $laptop = $this->db->query("SELECT name FROM products WHERE type = 'Laptop' ");


        $data = array();

        switch($product)
        {
            case 'camera' : 
            foreach ($camera->result() as $row)
            {
                $entry = array();
                $entry['name'] = $row->name;
                $data[] = $entry;
            }
            return $data; break;

            case 'laptop' :
            foreach ($laptop->result() as $row)
            {
                $entry = array();
                $entry['name'] = $row->name;
                $data[] = $entry;
            }
            return $data; break;

        }   
    }
4
  • Where is the code that prints the product on the screen? Commented Oct 19, 2012 at 17:52
  • no one has answered any of your previous questions correctly? Commented Oct 19, 2012 at 17:52
  • Let's see the code that outputs this result. Odd are you are doing something like <?php echo lookup(); ?>, which returns an array. You need to set the key... <?php $foo = lookup(); echo $foo['name']; ?> Commented Oct 19, 2012 at 17:52
  • Not an answer, since we can't see how you're outputting it. But it seems like you're doing extra work. Check to see if $product is camera or laptop before the query, then use either $product or a new variable in the query. Then you only need to run 1 query and you can eliminate that switch. Commented Oct 19, 2012 at 17:54

1 Answer 1

2

Are you trying to echo an array? You should probably try var_dump($array_var); or use a loop such as foreach to traverse the array values and print/echo each one.

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct. I like to use the print_r function. In some of my code, I create a print_ar() function that echos "<pre>" and "</pre>" before and after a print_r call. That makes the browser display the printed array nice enough for my purposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.