So I have a function that is supposed to have multiple parameters passed to it which are then multiplied by prices that come from an xml and are inserted into an array. The array works and everything but when I try to multiply the parameters by the value from the array...I get 0...

function min_calc($TRIT,$PYER,$MEXA,$ISOG,$NOCX,$ZYDR,$MEGA,$MORP)
{
 $TRIT_AVG = $TRIT*$arr[0];
 $PYER_AVG = $PYER*$arr[1];
 $MEXA_AVG = $MEXA*$arr[2];
 $ISOG_AVG = $ISOG*$arr[3];
 $NOCX_AVG = $NOCX*$arr[4];
 $ZYDR_AVG = $ZYDR*$arr[5];
 $MEGA_AVG = $MEGA*$arr[6];
 $MORP_AVG = $MORP*$arr[7];
 $total=$TRIT_AVG+$PYER_AVG+$MEXA_AVG+$ISOG_AVG+$NOCX_AVG+$ZYDR_AVG+$MEGA_AVG+$MORP_AVG;
 return $total;
}

Sorry for the ugly code, it's for eve online and so I used names I would remember. Ideally I would like to be able to do min_calc(300,0,0,0,0,166,333,0) and have it return the result of multiplying those by the indexed "price" in the array and summing them up.

The issue seems to be with how the array is being handled in the function...and I'm not sure what to do but it's probably something super simple that I'll smack my forehead over. Any help would be greatly appreciated.

    Hi Ark3typ3,

    If you want to access a variable that was defined outside the function, you need to use global declaration inside the function.

    function min_calc($TRIT,$PYER,$MEXA,$ISOG,$NOCX,$ZYDR,$MEGA,$MORP)
    {
         global $arr;
    
    --- rest of the code --
    
    }
    
    

    why dont you pass the array as an argument as well? 🙂

    Regards,
    niroshan

      niroshan wrote:

      you need to use global declaration inside the function.

      ...or, since global variable declarations are deprecated (and/or considered a bad coding practice), pass in the variables as arguments/parameters of the function.

        accessing it as a global variable worked like a charm, I definitely appreciate the help and in the interest of good code I did end up going with passing $arr as the last parameter of the function, incidentally this allows me to reuse this code for another portion of the site using the same calculations but different prices so now I can use either array. Thank you both those were exactly the answers I was looking for and I smacked my forehead in the process 🙂

          Write a Reply...