Search code examples
phpdivide-by-zero

Division By Zero


I'm using a method to calculate some scores. This is the following method:

public function getIntScore($name, $int){
    switch ($name) {
        case "bedrooms":
            $maxscore = 15;
            break;
        case "living_size":
            $maxscore = 10;
            break;
        case "property_size":
            $maxscore = 10;
            break;
        case "date_of_construction":
            $maxscore = 3;
            break;
    }
    $houseattribute = (int) $this->$name;
    $difference = abs($houseattribute - $int);
    if ($difference == 0) {
        return $maxscore;
    }
    $score = ($difference / $houseattribute) * $maxscore;
    return round($score);
}

However, this gives me a "Division by zero" error. I checked the values of the variables before calculating and none of them are zero.

var_dump($difference, $houseattribute, $maxscore) 

outputs:

int(2) int(3) int(15) 

Solution

  • Solved. I was stupid enough to forget I was looping through an array, where the first $houseattribute was 3. I had an item in my array where $houseattribute was 0, but because I used exit; after dumping the variables I didn't know it was. I changed it to a positive integer and not it's working.