Reputation: 13
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
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:
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.
$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
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