I have the following code which creates an array.
$qry="SELECT foo_id, foo1, foo2 FROM foo_table";
$result=mysql_query($qry);
while($row = mysql_fetch_array($result)){
extract($row);
$my_array[$foo_id] = array('foo1' => $foo1, 'foo2' => $foo2);
}
If I save this in a separate file (array.php) and then ‘include’ this in my code (example 1) everything works fine and $my_array can be called fine. If however I set this code up as a function (example 2) and call it from within my code and then try and use the array I get the message that $my_array has not been defined.
example 1 – displays the array
include 'array.php';
var_dump($my_array[1]);
example 2 – gets the error message Undefined variable: $my_array
function create_array(){
$qry="SELECT foo_id, foo1, foo2 FROM foo_table";
$result=mysql_query($qry);
while($row = mysql_fetch_array($result)){
extract($row);
$my_array[$foo_id] = array('foo1' => $foo1, 'foo2' => $foo2);
}
}
create_array();
var_dump($my_array[1]);
Am I doing something fundamentally wrong? I’m a bit new to php so simple explanations would be appreciated!!
Thanks
$my_arraybeing defined inside a function, doesn’t exists outside that function.Try add
return $my_array;increate_arry()function.Then call the function like this:
$my_array = create_arry();, to store data returned by that funnction in$my_arrayvariable.