# Problem with an array in a loop

0

I have a problem with an array in a loop and I wanted to simplify this code and they gave me a hand but I can not make the array correctly interpreted.

``````\$s = [0,0,0,0,0,0,0,0];
for (\$i = 0; \$i < count(\$Datos); \$i++) {
\$s1 += \$Datos[\$i]["Valor1"];\$s2 += \$Datos[\$i]["Valor2"];
\$s3 += \$Datos[\$i]["Valor3"];\$s4 += \$Datos[\$i]["Valor4"];
\$s5 += \$Datos[\$i]["Valor5"];\$s6 += \$Datos[\$i]["Valor6"];
\$s7 += \$Datos[\$i]["Valor7"];\$s8 += \$Datos[\$i]["Valor8"];
}
``````

This is the code and I do run it but the \$ s [\$ j] part is not interpreting correctly it is not giving it value so that it stays in \$ s1, \$ s2 and so and I wanted to know if you can take a I've tried a lot of cables and apparently it should run without problem.

``````\$s = [0,0,0,0,0,0,0,0];

for (\$i = 0; \$i < count(\$Datos); \$i++) {
for (\$j = 0; \$j < 8; \$j++) {
\$s[\$j] += \$Datos[\$i]["Valor" . (\$j+1)];
}
}
``````

Basically if I put the value \$ s [\$ j] manual if it runs fine but it would not work, I should go back to the previous code since I need it in multiple variables ...

Clarification:

The loop apparently should work but it does not correctly interpret \$ s [\$ j] that should result in \$ s1, \$ s2 and so on ...

asked by Vicente 06.11.2018 в 18:32
source

## 2 answers

0

Checking your code I see that you are not initializing your variables {s1, s2, ...}, I recommend you before executing the loop assign them to a value of zero `por ejemplo \$s1 = 0;` . It may be generating unexpected results by getting (garbage) when you execute the sum.

Likewise, edit the question to have more information, such as test cases, expected entry and exit values.

So, I can orient you better.

answered by 06.11.2018 в 19:03
0

a more efficient, clear and simple way to do what you want is with the use of the function list () of php:

``````list(\$s1,\$s2,\$s3,\$s4,\$s5,\$s6,\$s7,\$s8) = \$s;
``````

reference:
link

answered by 06.11.2018 в 19:23