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
https://forums.phpfreaks.com/topic/176234-passing-arrays-out-of-functions/
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;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.