Dino
Dino

Reputation: 1457

Php division by 0, help needed?

I keep getting division by 0 error in php.

I am currently using the following:

$ratio = 1/$rate["rate"];

the value $rate["rate"] is 0.827 (a value returned from a feed)

Please can anyone help with this.

Thanks

Upvotes: 1

Views: 74

Answers (2)

maček
maček

Reputation: 77826

if you're getting a division by 0 error, $rate['rate'] is most certainly or equivalent to 0. More likely than not, $rate['rate'] isn't getting set at all, and thusly you're trying to divide by an undefined value which is being cast to 0 for division.

To be sure, do a var_dump($rate['rate']) to see what it is.

Whenever you're doing a division operation that depends on a user input, I'd recommend validating the user input before attempting the division.

if(is_numeric($rate['rate']) && $rate['rate']!=0){
  $ratio = 1/$rate['rate'];
}
else {
  $ratio = 1;
}

See this code work on tehplayground.com

Upvotes: 3

Idan Arye
Idan Arye

Reputation: 12633

Make sure that $rate['rate'] is not converted to int somewhere along the way.

Upvotes: 0

Related Questions