How to compare two float arrays for exact equality in PHP

1 Answer

0 votes
/*
    Compare two float arrays element-by-element for exact equality.
    Floating‑point values must match exactly; even tiny rounding
    differences will cause inequality. This is stricter than using
    a tolerance-based comparison.
*/

/*
    Compares two float arrays and returns true only if all elements
    are exactly equal. Direct == comparison checks for exact binary equality.
*/
function compareFloatArraysExact(array $a, array $b): bool
{
    // If lengths differ, arrays cannot be equal
    if (count($a) !== count($b)) {
        return false;
    }

    // Compare each element directly
    for ($i = 0; $i < count($a); $i++) {
        if ($a[$i] !== $b[$i]) {
            return false;   // Found mismatch → arrays differ
        }
    }

    // All elements matched exactly
    return true;
}

/*
    Prints the comparison result.
*/
function printComparison(bool $result): void
{
    if ($result) {
        echo "Arrays are exactly equal.\n";
    } else {
        echo "Arrays differ.\n";
    }
}

// Example arrays
$floatArr1 = [
    12314.9872,
    3.14,
    12387.91834,
    8873.579013
];

$floatArr2 = [
    12314.9872,
    3.14,
    12387.91834,
    8873.579013
];

// Perform exact comparison
$result = compareFloatArraysExact($floatArr1, $floatArr2);

// Output result
printComparison($result);



/*
run:

Arrays are exactly equal.

*/

 



answered Sep 11 by avibootz
...