2

我有一个用户输入的数字列表。我想数一数并得到:

  1. 每个数字的小计(只有可能的数字是1, 2, 3, 4, 5),以及
  2. 所有输入数字的总和。

看:

// Outputs the numbers , " 1 4 1 1 5  " 
// for example (no commas, order is as inputed by user)
echo $a;

#1:

if ($a == "1"){
    $b++;

    // Outputs the actual count but in steps, 
    // say there are 3 "1" then it outputs: 1 2 3 , 
    // but I only want the 3. 
    echo $b;
}

如何覆盖递增的变量?然后我就有了我想要的东西,或者我错了。有更好/更清洁的方法吗?

#2:

// outputs only a bunch of 11111 
// (the right amount if i add them up)
echo count($a);

// outputs also a bunch of 111111
print strlen($a);

任何其他方式来计算和获得总数(不是总和,输入数字的总数)?

这几天我一直在想办法解决这个问题。显然,我是一个初学者,我很想了解。我检查了大约 5 本书和 php 在线手册。如果有人能引导我朝着正确的方向前进,我将不胜感激。请 :)

4

1 回答 1

3

这将满足您的要求。它将数字拆分为一个数组,使用 array_sum 计算所有元素,然后使用数组的大小来计算元素的总数。它还使用 trim 来清除用户可能输入的任何空白。

$split_numbers = explode(' ',trim($a));
$total_added = array_sum($split_numbers);
$total_numbers = sizeof($split_numbers);

您可以在此处查看此代码的运行情况。

于 2011-12-07T00:41:37.107 回答