Jump to content

Passing arrays out of functions


jmanfffreak

Recommended Posts

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.

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

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;
}

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.