Receiving an array as a parameter in a PHP function

Asked

Viewed 1,121 times

-1

Well, the subject may be old, but that doubt has arisen, not patience in rewriting the code...

The following code is not generating a result.

There’s a function that’s basically 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;
}           

She’s being called this way:

$Preco1=Preco($matrizPrecos);

The function receives an array containing the prices...

Within the function 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 "house array".

Return the result.

Thanks for your attention!

  • Okay. What’s the problem ?

  • Doesn’t work...

  • I believe information is missing. You do a foreach on $faixaEtaria Where does that come from? And why do you have a & as a function parameter ?

  • $faixaEtaria is another array, never zeroed. The "&" would be to refer to the address, since putting normally was not working (as it still does not work). Except "$soma[]", all arrays exist and have content in the code.

2 answers

2


I populated the arrays with fictitious values to find out if there was any error. And I found some. Follow 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’ve helped.

  • Putz! Thanks! I’ll test it here! Lack of attention in $sum!

  • I hope I’ve helped ; )

  • Brother, I got it. The problem is in $faixaxaEtaria. Inside the function after $soma=array(); I put: global $faixaEtaria; So I catch it "out there". Thanks ae!

  • Good. I’m glad I contributed.

0

After the help of Ricardo Mota, he only had 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;
}   

Browser other questions tagged

You are not signed in. Login or sign up in order to post.