user947462
user947462

Reputation: 949

Warning: Division by zero in loop

I have this code:

for ($y = 0; $y < $numRows; $y++) {
    for ($i = 0; $i < $numRows; $i++) {
        ${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[$y];
    }
}

echo $contaH0[0]."\n";

that output is:

Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
Warning: Division by zero in C:\Users\xx\VertrigoServ\www\AHP\new\demo.php on line 66
0.300618921309 

but if i change this line:

${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[$y];

to

${'contaH' . $i}[]=${'arrHoriz' . $i}[$y]/$arr[0];

the output is:

0.300618921309 

What is the reason of the warning in first code ?

Upvotes: 0

Views: 982

Answers (2)

CanSpice
CanSpice

Reputation: 35808

The reason is that in your loop, $arr[$y] isn't always equal to 0. Somewhere in your array it's zero (or not defined). You should do a check to see if your denominator is zero before doing any division and properly handle the case where it's zero.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798764

Either $arr doesn't have as many elements as you think it does, or it has a lot of 0 or empty elements.

Upvotes: 3

Related Questions