Receiving an array as a parameter in a PHP function

-1

Well, the subject may be old but there was this doubt and not patience in rewriting the code ...

The following code is not generating results.

There is a function that basically looks like this:

function Preco(&$p)
{
$soma=array();

    foreach ($p as $pcos):
        foreach($faixaEtaria as $qtde):

            $soma=$pcos*$qtde;

        endforeach;
    endforeach;

$resultado=array_sum($soma);

return $resultado;
}           

It is being called this way:

$Preco1=Preco($matrizPrecos);

The function receives an array containing prices ...

Within the function I create another array, whose elements receive the product between that price array and an array of 'quantities', each.

After, I only ask for the sum of the elements of this "home" array.

I return the result.

Thank you for your attention!

    
asked by anonymous 19.07.2016 / 22:10

2 answers

2

I populated the arrays with dummy values to see if there were any errors. And I found some. Here is the corrected code that returns the values:

        function Preco($p){
            //$faixaEtaria = array(10, 20);
            $soma = array();

            foreach ($p as $pcos):
                foreach($faixaEtaria as $qtde):

                    $soma[] = $pcos * $qtde;

                endforeach;
            endforeach;

            $resultado = array_sum($soma);
            return $resultado;
        } 

        //$matrizPrecos = array(5, 10, 15, 5);
        $Preco1 = Preco($matrizPrecos);

        echo $Preco1;

I hope I have helped.

    
19.07.2016 / 22:44
0

After the help of Ricardo Mota, just needed to add the "global" .. the code returns result now:

 function Preco($p)
{
$soma=array();

global $faixaEtaria;

    foreach ($p as $pcos):
        foreach($faixaEtaria as $qtde):

            $soma[]=$pcos*$qtde;
        endforeach;
    endforeach;

$resultado=array_sum($soma);

return $resultado;
}   
    
19.07.2016 / 23:09