How to determine if a string has all unique characters in PHP

2 Answers

0 votes
function all_unique_chars($s) {
    $ascii = array_fill(0, 256, 0);
    $size = strlen($s);
   
    for ($i = 0; $i < $size; $i++) {
        $ascii[ord($s[$i])] += 1;
        if ($ascii[ord($s[$i])] > 1)
            return false;
    }
    
    return true;
}
    
$str = "php javascript";
    
echo (all_unique_chars($str)) ? "yes" : "no";
 
 
 
   
   
   
/*
run:
   
no
   
*/

 



answered May 5, 2022 by avibootz
edited May 7, 2022 by avibootz
0 votes
function all_unique_chars($s) {
    $arr = str_split($s);
    sort($arr);
    $s = implode($arr);
     
    $size = strlen($s);
     
    for ($i = 0; $i < $size - 1; $i++) {
        if ($s[$i] == $s[$i + 1]) {
            return false;
        }
    }
    return true;
}
   
$str = "php javascript";
   
echo (all_unique_chars($str)) ? "yes" : "no";

echo "\n";

echo (all_unique_chars("abcd")) ? "yes" : "no";
  
  
  
  
/*
run:
  
no
yes
  
*/

 



answered May 5, 2022 by avibootz

Related questions

1 answer 134 views
1 answer 129 views
1 answer 151 views
1 answer 122 views
1 answer 123 views
...