CodeIgniter Forums
How to store array values in a foreach loop - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: How to store array values in a foreach loop (/showthread.php?tid=67202)



How to store array values in a foreach loop - kayinja.denis - 01-26-2017

Hello everyone, am  new to codeignitor, am getting trouble in storing values in array. below is my code

PHP Code:
$query $this->db->query('SELECT name FROM grade');
$data     array();
foreach (
$query->result_array() as $row):                                                     
            $data
[] = array('name' => $row->name);
 
            //echo $data['name']; //I get all the values in a column
endforeach; 

 
             echo $data['name']; //I get only the last value 
 When i echo $data['name'];  inside the loop, I get all the values but when I call it outside a loop I get only one
last value in the column. I want to pass this array with all it's values to another block of code.
any suggestion is welcomed.


RE: How to store array values in a foreach loop - Wouter60 - 01-26-2017

PHP Code:
$query $this->db->query('SELECT name FROM grade');
$data     array();
foreach (
$query->result_array() as $row):                                                     
            $data
[] = $row['name'];
endforeach; 
Echo 
'<pre>';
Print_r($data);
echo </
pre>' ;
// this will output the entire array $data 

Alternative method:
PHP Code:
$query $this->db->query('SELECT name FROM grade')->result_array();
$data array_column($query'name'); 



RE: How to store array values in a foreach loop - kayinja.denis - 01-26-2017

@Wouter60, thanks very much they worked.  Smile Smile Smile Smile