Skip to content
PHP Logo

How can you optimize the code provided to ensure accurate comparison of string values in PHP arrays?

When comparing string values in PHP arrays, it is important to ensure that the comparison is case-insensitive to avoid any discrepancies. One way to optimize the code is to use the `strcasecmp()` function, which compares two strings case-insensitively. This function returns 0 if the two strings are equal, regardless of case.

php
$array1 = ["Apple", "Banana", "Orange"];
$array2 = ["apple", "banana", "orange"];

// Check if the arrays are equal regardless of case
$equal = true;
if(count($array1) == count($array2)){
    for($i = 0; $i < count($array1); $i++){
        if(strcasecmp($array1[$i], $array2[$i]) != 0){
            $equal = false;
            break;
        }
    }
} else {
    $equal = false;
}

if($equal){
    echo "The arrays are equal.";
} else {
    echo "The arrays are not equal.";
}