# Problem with array in PHP

1

I have a problem using array.
I am trying to add the average score of 'persona1'+'persona2' and divide the result by the number of people so that I can print the average number of notes between these two people. But, the result is not what I expect since it shows me the average of 'persona1' and then the average between 'persona1'+'persona2' .

\$persona1 = [
'nombre' => 'nombre1',
'notas' => [1,2,3,4]
];

\$persona2 = [
'nombre' => 'nombre2',
'notas' => [5,6,7,8]
];

\$persona3 = [
'nombre' => 'nombre3',
'notas' => [5,1,3,4]
];

\$datos=[\$persona1, \$persona2, \$persona3];

\$suma = 0;

foreach(\$datos as \$persona){

\$media = array_sum(\$persona['notas'])/count(\$persona['notas']);

\$suma = \$suma + \$media;

echo \$suma . " ";

}
}

// El resultado que me muestra es : 2.5 9
// El resultado que necesito es : 9
// No entiendo por que me muestra ese 2.5, el 2.5 entiendo que es la suma de las notas de persona1 divida entre el numero de notas.

asked by InThaHouse 30.11.2018 в 20:35
source

2

Your logic is correct, at the end the variable saves the value of 9 which is what you need but you are printing it in the first iteration so it shows you

2.5 9

which is the result in each iteration, just print the variable \$suma out of the foreach and it will show you the correct result:

\$persona1 = [
'nombre' => 'nombre1',
'notas' => [1,2,3,4]
];

\$persona2 = [
'nombre' => 'nombre2',
'notas' => [5,6,7,8]
];

\$persona3 = [
'nombre' => 'nombre3',
'notas' => [5,1,3,4]
];

\$datos=[\$persona1, \$persona2, \$persona3];

\$suma = 0;

foreach(\$datos as \$persona){

\$media = array_sum(\$persona['notas'])/count(\$persona['notas']);

\$suma = \$suma + \$media;

//echo \$suma . " ";

}
}
//Imprimes luego de que realizas todas las iteraciones
echo(\$suma);//Imprime 9