slancasterfreak Posted October 6, 2007 Share Posted October 6, 2007 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!!!! Quote Link to comment https://forums.phpfreaks.com/topic/72086-cant-get-my-array-out-of-my-function/ Share on other sites More sharing options...
MadTechie Posted October 6, 2007 Share Posted October 6, 2007 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); Quote Link to comment https://forums.phpfreaks.com/topic/72086-cant-get-my-array-out-of-my-function/#findComment-363292 Share on other sites More sharing options...
recklessgeneral Posted October 6, 2007 Share Posted October 6, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/72086-cant-get-my-array-out-of-my-function/#findComment-363293 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.