How to find the first character that is repeated in a string with PHP

1 Answer

0 votes
function get_first_character_repeated($s) { 
    $len = strlen($s);
            
    for ($i = 0; $i < $len; $i++) { 
       for ($j = $i + 1; $j < $len; $j++) { 
            if ($s[$i] == $s[$j]) { 
                return $i;
            } 
        } 
    } 
    return -1; 
}  
 
$s = "abcdxypcbop"; 
         
$i = get_first_character_repeated($s); 
        
if ($i == -1) {
    echo "Not found"; 
}
else {
     echo $s[$i];
}


    
/*
run:

b
         
*/

 



answered Jan 25, 2020 by avibootz
edited Jan 26, 2020 by avibootz

Related questions

...