Jump to content

newbie problem - returning array value from function....help?


Recommended Posts

I have what I'm sure is a simple fix for an experienced PHP person. I have a function whose purpose is to return an array of values to be used elsewhere on a page, but I can't seem to get it to ouput the array. (When I try to reference the $territory variable outside the function I get nothing.)

Here's my function:

 

function get_territory_names() {

$territory = array();

$sql = "SELECT terr_id, name FROM territories";

$result = mysql_query($sql) or die ("Error in query: $sql. " . mysql_error());

while ($row = mysql_fetch_object($result)) {

$key = $row->terr_id;

$value = $row->name;

$territory[$key] = $value;

}

return $territory;

}

 

$territory is supposed to hold about 12 key/value pairs.

I've replaced "return $territory" with "var_export($territory)" and see that the array is populated correctly....so I guess my question is just how do I get the array out of the function so I can reference it elsewhere on the page?

Any help is very much appreciated!!

 

Your function returns a value so what you want to do is this when you call your function

 

$my_array = get_territory_names();

 

$my_array will be passed the value of $territory created in the function.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.