phparrayscodeigniter

extracting value from array in codeigniter


When I dump my the varable

var_dump($search_results_returned['post_q_2_full']);

the following is printed:

  array(1) { 
          [0]=> array(7) {
                     ["user_id"]=> string(2) "15" 
                     ["user_name"]=> string(12) "Steve Smith" 
                     ["user_username"]=> string(8) "sjcallan" 
                     ["user_image_filename"]=> string(16) "xhewimg_15.jpeg"     
                     ["user_first_name"]=> string(5) "Steve"
                     ["user_last_name"]=> string(6) "Smith" 
                     ["user_email"]=> string(18) "ssmith@gmail.com" 
          }
    } 

When I am trying

foreach ($post_q_2_full as $post2) { // line 48

echo $post2['user_first_name'];
}

I am getting the following error:

============================================
Message: Undefined variable: post_q_2_full

Filename: _account/search.php

Line Number: 48
============================================

And the following error message as well:

Message: Invalid argument supplied for foreach()

Filename: _account/search.php

Line Number: 48

How to resolve this?


Solution

  • You are trying to do a foreach loop on a variable that does not exist. post_q_2_full is the key inside $search_results_returned variable, and not a variable on it's own.

    So what you're looking for is this:

     <?php
     foreach ($search_results_returned['post_q_2_full'] as $post2) { // line 48
        echo $post2['user_first_name'];
     }
    

    Note: IMHO the variable name is too long, so I would try to shorten that in the actual production code.