PHP:计算字符串中的不同数字

时间:2016-05-14 15:57:52

标签: php

我有一个像这样的字符串:

  

,10,10,10,10,10,10,10,11

我如何计算有多少不同的数字?

4 个答案:

答案 0 :(得分:0)

//remove the starting from the given string,
$input = substr($input, strpos(',', $input) + 1);

//split the string on ',' and put it in an array
$numbers = explode(',', $input);

//an array to put our unique numbers in
$counter = array();
//for each number
foreach($numbers as $number) {
  //check if it is not in the unique 'counter' array
  if(!in_array($number, $counter)) {
    //remember this unique number
    $counter[] = $number;
  }
}

//count the unique number array
$different = count($counter);
//give some output
echo "There are " . $different . " unique numbers in the given string";

输入变量应该是您的文字,因为您的文字以','开头。我们将它从输入字符串中删除

答案 1 :(得分:0)

你可以使用explode函数使string成为一个数组,然后在其上使用array_unique函数来获取它的唯一数字。通过此阵列阵列,您可以轻松计算您的唯一数量。

$str = ",10,10,10,10,10,10,10,11";

$arr = explode(",", trim($str, ","));

$arr = array_unique($arr);

print_r($arr);

<强>结果:

Array
(
    [0] => 10
    [7] => 11
)

所以现在是时候计算了,只需使用count

echo count($arr);// 2

答案 2 :(得分:0)

  1. explode string ,
  2. 上的array_filter
  3. array_unique没有回调,删除空匹配(第一个逗号)
  4. count删除重复值
  5. array_unique返回$string = ",10,10,10,10,10,10,10,11"; echo count(array_unique(array_filter(explode(",", $string))));
  6. 的大小
    {{1}}

答案 3 :(得分:-1)

尝试这样的事情:

$string = '10, 10, 11, 11, 11, 12';

$numbers = explode(',',$string);
$counter = array();
foreach($numbers as $num) {
   $num = trim($num);
   if (!empty($num)) {
      if (!isset($counter[$num])) {
         $counter[$num]=1;
      } else {
         $counter[$num]++;
      }
   }
}

print_r($counter);

希望这有帮助!

相关问题