Jump to content

[SOLVED] Getting an array from within a function..


Dragen

Recommended Posts

Hi,

I've got this function which gets an array

<?php
//get variable arrays from database
function get_variable_arrays($varname){
$sql = "SELECT * FROM variables WHERE `name` = '" . $varname . "' ORDER BY `value` ASC";
if($result = mysql_query($sql)){
	if(mysql_num_rows($result) > 0){
		while($row = mysql_fetch_assoc($result)){
			$variable[$varname][$row['value']] = $row['value'];
		}
	}else{
		echo 'ERROR: array not found!';
	}
}else{
	echo mysql_error();
}
}
?>

I think I'm doinf something wrong when calling it as I'm trying to then use the array I've created.

If I try:

<?php
get_variable_arrays('adspacea');
print_r($variable);
?>

I just get nothing. I've tried putting a return in my function, but think I'm doing it wrong.

Could someone help me to get the $variable array I've created to use it?

 

Thanks

<?php

function get_variable_arrays($varname){
$variable = array();
$sql = "SELECT * FROM variables WHERE `name` = '" . $varname . "' ORDER BY `value` ASC";
if($result = mysql_query($sql)){
	if(mysql_num_rows($result) > 0){
		while($row = mysql_fetch_assoc($result)){
			$variable[$varname][$row['value']] = $row['value'];
		}
		return $variable;
	}else{
		echo 'ERROR: array not found!';
		return false;
	}
}else{
	echo mysql_error();
	return false;
}
}

$resultarray = get_variable_arrays('adspacea');

if($resultarray) {
print_r($resultarray);
} else {
echo "An error occured...";
}

?>

You have not coded your function to return anything and thus you are getting nothing.

 

Functions have there own scope so any variables you set in the function will not be abled to be accessed globaly unless you set them as global or return the variable.

 

EDIT: I'd change your code to this:

<?php
//get variable arrays from database
function get_variable_arrays($varname)
{
    $sql = "SELECT * FROM variables WHERE `name` = '" . $varname . "' ORDER BY `value` ASC";

    $result = mysql_query($sql) or die(mysql_error());

    if(mysql_num_rows($result) > 0)
    {
        while($row = mysql_fetch_assoc($result))
        {
    	    $variable[$varname][$row['value']] = $row['value'];
        }

        return $variable;
    }
    else
    {
        return false;
    }
}

$arrayVar = get_variable_arrays('adspacea');

if(is_array($arrayVar))
{
    print_r($arrayVar);
}
else
{
    echo 'No results returned';
}

?>[code]

[/code]

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.