Alif Laksono
Alif Laksono

Reputation: 13

Warning Division By zero

I'm building support decision system using electre method While i compile my code i got an error the error is : Warning Division By zero Here is the function that i created

function normalisasi(){
    $array = ratarata();
    $arr = spk_rel();
    $nilai = array();
    $data = array();

    foreach ($array as $key => $value) {
        $nilai[$key]=sqrt(array_sum($value));
    }
    foreach($arr as $key => $value){                
        foreach($value as $k => $v){
           $data[$key][$k] = $v / $nilai[$k];
        }
    }
    return $data;
}

The error is in

$data[$key][$k] = $v / $nilai[$k];

could you please help me ?

Upvotes: 0

Views: 530

Answers (2)

Konrad Gałęzowski
Konrad Gałęzowski

Reputation: 1983

You didn't specified what the logic is about, but if you're expecting some values of $nilai to be 0 and you can just skip them, there 2 ways to achieve that:

  1. Checking for value inside loop
    foreach($arr as $key => $value){                
        foreach($value as $k => $v){
           if ($nilai[$k]) {
               $data[$key][$k] = $v / $nilai[$k];
           }
        }
    }

This expression if ($nilai[$k]) will be true when $nilai[$k] is either positive or negative and will be false when it's 0.

  1. You can remove 0 values from $nilai array before loop
    foreach ($array as $key => $value) {
        $nilai[$key]=sqrt(array_sum($value));
    }

    $nilay = array_filter($nilay);

    foreach($arr as $key => $value){
        ...
    }

In this case array_filter called without second argument (filter callback) will just remove all 0 values from array passed as first argument.

Upvotes: 0

Trần Hữu Hiền
Trần Hữu Hiền

Reputation: 1044

You will get a error when you divide any by 0.

You should check $nilai[$k] before make a divide by 0.

if (!empty($nilai[$k])) {
  $data[$key][$k] = $v / $nilai[$k];
}

Upvotes: 1

Related Questions