What are some alternative approaches to detecting duplicate characters in a string using PHP?

One alternative approach to detecting duplicate characters in a string using PHP is by using the array_count_values() function to count the occurrences of each character in the string. Then, we can loop through the resulting array and check if any character occurs more than once.

function hasDuplicateCharacters($str) {
    $charCounts = array_count_values(str_split($str));
    
    foreach ($charCounts as $char => $count) {
        if ($count > 1) {
            return true;
        }
    }
    
    return false;
}

// Example usage
$string = "hello";
if (hasDuplicateCharacters($string)) {
    echo "String contains duplicate characters";
} else {
    echo "String does not contain duplicate characters";
}