PDA

View Full Version : Call Array Value From Outside Function?


Mink_
02-16-2005, 01:08 AM
I'm working on a web-RPG, and need a little help with my database queries, as I need to be setting up globals using unfctions.

I'm using this simple code that I came up with after a few minutes of looking at the PHP manual (I've already set the database up):

function getuserinfo($id) {
$query = mysql_query("SELECT * FROM users WHERE id = $id LIMIT 1");
$user = mysql_fetch_array($query);
}

Then, I want to call values from that by using things like $user['var'].
The only problem is, I can only seem to call values from that array inside the function, meaning that this will work:

function getuserinfo($id) {
$query = mysql_query("SELECT * FROM users WHERE id = $id LIMIT 1");
$user = mysql_fetch_array($query);
echo $user['var'];
}
getuserinfo(1);

And this will not:

function getuserinfo($id) {
$query = mysql_query("SELECT * FROM users WHERE id = $id LIMIT 1");
$user = mysql_fetch_array($query);
}
getuserinfo(1);
echo $user['var'];

Is there an alternate way of getting the results I would see if the second bit of code worked? Or do I have to redesign my entire system? :rolleyes:

amykhar
02-16-2005, 01:14 AM
You could set up the user variable outside the function and pass it in to be filled or you could return the user variable. The way you have it set up now, its scope is only within the function.

Mink_
02-16-2005, 01:22 AM
You could set up the user variable outside the function and pass it in to be filled or you could return the user variable.

The reason I wanted to do this with arrays is that I need to have something like 100 global variables for my software, and setting them up individually would be a pain. They're taken directly from the MySQL database, and then turned into arrays, meaning I couldn't really set up that value elsewhere...

amykhar
02-16-2005, 01:35 AM
You can pass arrays in and out just like any other variable.

Mink_
02-16-2005, 02:06 AM
You can pass arrays in and out just like any other variable.
I'm having trouble passing the variables out. oO;
for instance,

function test() {
$var = "val";
}
test();
echo $var;

doesn't work. :(

amykhar
02-16-2005, 02:15 AM
function test should have a return line in it that returns $var.

The code would look like:


function test() {
$var = "val";
return $var;
}
$othervar = test();
echo $othervar;

Mink_
02-16-2005, 02:21 AM
Thanks alot. :)
You rule. This will help me infinitely. As the English say, cheers! :D