PHP字符串去重,统计没有分割符的字符串不重复的个数

PHP字符串去重,统计没有分割符的字符串不重复的个数

统计没有分割符的字符串不重复的个数
<?php
//没有分割符的字符串转成数组
$opennum = '45842';

$arr = str_split($opennum);
//去重
$arr = array_unique($arr);
//统计个数
$ncount = count($arr);
//打印结果
var_dump($opennum.' c='.$ncount);
?>

<?php  
//使用内置函数
//公共函数:字符串去重函数 
function unique($str){ 
    //字符串中,需要去重的数据是以数字和逗号连接的字符串,如$str,explode()是用逗号为分割,变成一个新的数组,见打印 
    $arr = explode(',', $str); 
    $arr = array_unique($arr);//内置数组去重算法 
    $data = implode(',', $arr); 
    $data = trim($data,',');//trim — 去除字符串首尾处的空白字符(或者其他字符),假如不使用,后面会多个逗号 
    return $data;//返回值,返回到函数外部 
}

$str = '1,2,3,3,5,4,5,4,7,6,4,5'; 
echo unique($str);

?>

使用内置函数,可以很方便的得到预期的效果, 打印出来的结果如下:
1,2,3,5,4,7,6

原文地址:https://www.cnblogs.com/zdz8207/p/php-str_split-array_unique-count.html