Jump to content

Return array from function


WillyTheFish

Recommended Posts

Okay, I know this is extremely simple but I tried the return() function and all that, but it just won't work...

How do I pass a variable or an array from a function to the global scope?

 

	
<?php
function db_getcol($db_database,$db_tablename)
{	
	$db_fields = mysql_list_fields($db_database,$db_tablename);
	$db_columns = mysql_num_fields($db_fields);

	for ($n=0;$n<=$db_columns-1;$n++)
	{
		$field_array[] = mysql_field_name($db_fields,$n);
	}

		return $field_array;
}

var_dump($field_array);
?>

 

as you see, I'm trying to get a var_dump() of $field_array, which is defined within the function...

Thanks in advance :)

Link to comment
https://forums.phpfreaks.com/topic/190854-return-array-from-function/
Share on other sites

You need to call the function, if you wish to access the returned data using a variable in the global scope, you need to assign the returned data to a variable. i.e.

 

 

$arrField = db_getcol($db_database, $db_tablename);
var_dump($arrField);


// or if you simply wish to var_dump() it


var_dump(db_getcol($db_database, $db_tablename));


 

 

If you really wish to make the data global, use the global keyword, although you will still need to make a call to the function before using the global var

 

 

<?php
function db_getcol($db_database,$db_tablename)
   {   
      $db_fields = mysql_list_fields($db_database,$db_tablename);
      $db_columns = mysql_num_fields($db_fields);
      
      for ($n=0;$n<=$db_columns-1;$n++)
      {
         $field_array[] = mysql_field_name($db_fields,$n);
      }
      
         global $field_array;
   }


db_getcol($db_database,$db_tablename);

var_dump($field_array);
?>

 

 

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.