jmanfffreak Posted October 1, 2009 Share Posted October 1, 2009 I have the following code from another topic in my function: <?php function ServerStatus($server) { $s_nameid = '1'; // first Server ID (ALWAYS Should be '1') ......// trimmed if ($l_status < 0 || $c_status < 0 || $m_status < 0) { $s_status = array( $s_name => 'Online'); } else { $s_status = array( $s_name => 'Offline'); } foreach($server as $k => $v) { ......//trimmed if ($l_status < 0 || $c_status < 0 || $m_status < 0) { $s_status = array( $s_name => 'Online'); } else { $s_status = array( $s_name => 'Offline'); } } return $s_status; } ?> And here is the code calling that function: <div id="about-box"> <h2>Server Status</h2> <?php ServerStatus($server); foreach($s_status as $k => $v) { echo $k.":".$v; }?> </div> But for some odd reason, I'm getting the following error: Warning: Invalid argument supplied for foreach() in /home/mystonli/public_html/new/cp/header.php on line 49 Is there something I'm doing wrong? Can I not return an array from the function or am I just not defining it right? I have simply tried defining it with the format: $s_server[$s_nameid] = 'Online'; but that doesn't work either. Quote Link to comment https://forums.phpfreaks.com/topic/176234-passing-arrays-out-of-functions/ Share on other sites More sharing options...
Alex Posted October 1, 2009 Share Posted October 1, 2009 You should learn more about scopes, as that's your issue. The variable within the function isn't accessable outside of that scope, but since you're returning all you need to do is: $s_status = ServerStatus($server); Quote Link to comment https://forums.phpfreaks.com/topic/176234-passing-arrays-out-of-functions/#findComment-928766 Share on other sites More sharing options...
TeNDoLLA Posted October 1, 2009 Share Posted October 1, 2009 Yes you can return array from function and yes you are doing it wrong. You have to assign the returned array to variable before using it. Now you are trying to pass non-existant array to the foreach. Since the $s_status is only visible inside the function definition. <?php $returnedArray = ServerStatus($server); foreach($returnedArray as $k => $v) { echo $k.":".$v; } Quote Link to comment https://forums.phpfreaks.com/topic/176234-passing-arrays-out-of-functions/#findComment-928767 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.