-1

I am trying to modify an entire associative array with a function.

This is how the array looks like:

Array ( [3] => 11 [1] => 12 [2] => 23 [0] => 34 [4] => 42 )

And this is the function:

$bfactor = end($fballs) * log(100); 
function bexponential($bn) {    
    return(exp($bfactor / $bn));
}

$fballs = array_map("bexponential", $fballs);

It first calculates a $bfactor by multiplying the last element of the array by log(100) and then calculates the exponential of that $bfactor divided by each element of the array.

The function and the array_map work with simple operators like multiplications and divisions but not with the exponential function.

What is wrong with it?

mirix
  • 511
  • 1
  • 5
  • 13

1 Answers1

1

$bfactor is not available within your bexponential function.

You need to do this:

$bfactor = end($fballs) * log(100); 

function bexponential($bn) { 
  global $bfactor;   
  return exp($bfactor / $bn);
}

$fballs = array_map("bexponential", $fballs);

Alternatively:

$bfactor = end($fballs) * log(100); 

function bexponential($bn) {    
  return exp($GLOBALS['bfactor'] / $bn);
}

$fballs = array_map("bexponential", $fballs);

Or, if you don't need the bexponential function anywhere else, in one go:

$bfactor = end($fballs) * log(100); 

$fballs = array_map(function ($bn) use ($bfactor) {
  return exp($bfactor / $bn);
}, $fballs);
Jeto
  • 14,596
  • 2
  • 32
  • 46