Jump to content

Can't get my array out of my function


slancasterfreak

Recommended Posts

I am new to functions, and have been doing ok until I tried to return an array. 

 


function WalkerArray () {
       require('connecttodatabasea.inc.php');
       // get Walkers names into an array
       $queryx=("SELECT * FROM walkers ORDER BY id ASC");
       $resultx=mysql_query($queryx)  or die(mysql_error());
       $numx=mysql_numrows($resultx);
       $k=0;
       while ($k<$numx) {
              $id=mysql_result($resultx,$k,"id");
              $firstname=mysql_result($resultx,$k,"firstname");
              $lastname=mysql_result($resultx,$k,"lastname");
              $walkerarray[$id]=$firstname.' '.$lastname;
              $k++;
              }
       print_r($walkerarray);
       return $walkerarray;
       }



// now try to use function and see if I have the array and can print it out

WalkerArray();
print_r($walkerarray);

$idnum=50;
echo $walkerarray[$idnum];

 

The print _ r command INSIDE the function outputs the complete array, so I know my Mysql etc. is good.

But the second print _ r OUTSIDE the function prints nothing

 

I've searched for answers online and cannot figure it out. Thanks for the help!!!!

Link to comment
Share on other sites

your currently returning the array to nothing.. as has you want the returned results.. try this

$walkerarray = WalkerArray(); // <---
print_r($walkerarray);

 

thus $walkerarray is now the array

of course you could use any variable, ie

$MT = WalkerArray(); // <---
print_r($MT);

Link to comment
Share on other sites

Hi,

 

The $walkerarray variable is local to the WalkerArray function, so it can only be used in the scope of that function. In order to use it (or more precisely, a copy of it) outside the function, you assign the result of the function to a new variable and that will then work:

 

$walkerarray = WalkerArray();
print_r($walkerarray);

 

This should now print the same results as inside the function. The point to bear in mind is that the $walkerarray in the code above is a different variable to the one declared in the function.

 

Cheers,

Darren.

Link to comment
Share on other sites

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.