Here's a PHP code snippet to find the first non-repeating character in a string:
<?php
function firstNonRepeatingCharacter($str) {
$charCount = array();
// Count occurrences of each character in the string
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if (isset($charCount[$char])) {
$charCount[$char]++;
} else {
$charCount[$char] = 1;
}
}
// Find the first non-repeating character
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($charCount[$char] === 1) {
return $char;
}
}
// If no non-repeating character is found
return null;
}
// Example usage:
$string = "aabbccdeeff";
$result = firstNonRepeatingCharacter($string);
if ($result !== null) {
echo "The first non-repeating character is: $result\n";
} else {
echo "No non-repeating character found in the string.\n";
}
?>
Comments
Post a Comment