A
A
Adil16032020-05-03 19:35:27
PHP
Adil1603, 2020-05-03 19:35:27

Why did the negative number become positive when displaying the sum of for?

<?php
$arr = [1,3,5,6,7,8,9,1,2,-3];

$summa=0;
for ($i=0;$i<10;$i++){
  $summa+=$i;

}
echo 'summa tchisel massiva = '.$summa;


?>

The sum should have been 39, but outputs 45

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2020-05-03
@Adil1603

You are summing the $i index in the for, not the elements of the $arr[$i] array :)

<?php
$arr = [1,3,5,6,7,8,9,1,2,-3];

$summa=0;
for ($i=0;$i<10;$i++){
  $summa+=$arr[$i];

}
echo 'summa tchisel massiva = '.$summa;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question