0

I am facing one weird issue, sum of array is 1 but when I checking it into the IF condition it returns false.

$array = array
(
    0 => 0.237,
    1 => 0.318,
    2 => 0.215,
    3 => 0.06,
    4 => 0.069,
    5 => 0.053,
    6 => 0.048
);

if(array_sum($array) != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}

Above code is returning It's not one instead of It's one.

Jimesh Gajera
  • 612
  • 1
  • 11
  • 32

2 Answers2

1

Try this solution

$sum=number_format(array_sum($array));
if($sum != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}
josephthomaa
  • 158
  • 1
  • 11
1

You cannot compare float values without rounding them. See more here >> http://php.net/manual/en/language.types.float.php

You can do it as below,

$array = array
(
    0 => 0.237,
    1 => 0.318,
    2 => 0.215,
    3 => 0.06,
    4 => 0.069,
    5 => 0.053,
    6 => 0.048
);

if(round(array_sum($array)) != 1){
    echo "It's not one";
} else {
    echo "It's one"; 
}
Nuwan Attanayake
  • 1,161
  • 9
  • 20