0

I'm attempting to pass the denominator variable to the function convert. When I do, the returned array "$new_arr" produces "0" for each value.

I have tried replacing the variable $denominator with a digit within the function and the new array returns with the appropriate numbers.

My experience with PHP is novice so my questions are:

1) Is this an issue of scoping? I thought by declaring these variables outside of the function, they were inherently global.

2) Do I need to pass '$denominator' as an argument as well?

Thanks in advance. Here's the code.

$highest_val = max($array_1);
$lowest_val  = min($array_2);
$denominator = $highest_val - $lowest_val;

function convert($arr)
{

$new_arr=array();

for($i=0, $count = count($arr); $i<$count; $i++)
{
$numerator  = $arr[$i]-$lowest_val;     
$calc   = $numerator/$denominator;
$new_arr[] .= $calc;    
}
$arr = $new_arr;
return $arr;        
}

 $test_arr = convert($open_array);
 var_dump($test_arr);

2 Answers 2

2

To use Global variables inside your function, you need to define them global there too. Like this

$highest_val = max($array_1);
$lowest_val  = min($array_2);
$denominator = $highest_val - $lowest_val;
function convert($arr)
{
global $highest_val;
global $lowest_val ;
global $denominator;

Or you can simply send those three values as parameters to your function. You can also use $GLOBALS array if you follow the global scope path

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome, thanks! I can't accept it as an answer but I definitely will after the 10 minutes. If I forget, just pm me lol.
0

Yes, you do need to pass in the values as parameters into the function.

function convert($arr, $highest_val, $lowest_val, $denominator) { ... }

$test_arr = convert($open_array, $highest_val, $lowest_val, $denominator);
var_dump($test_arr);

1 Comment

Thanks for the answer! I appreciate the input at such a late hour.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.