计数和总计
我有一个用户输入的数字列表。我想对它们进行计数并得到:
- 每个数字的小计(仅可能的数字是
1, 2, 3, 4, 5
),以及 - 所有输入数字的总计。
请参阅:
// 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书籍和php在线手册。如果有人能引导我走向正确的方向,我将不胜感激。请 :)
I have a list of numbers that are inputted by users. I want to count them and get:
- Subtotals for each number (only numbers possible are
1, 2, 3, 4, 5
), and - a total of all inputted numbers.
See:
// 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;
}
How can I overwrite the incremented variable? Then I kind of have what I want or am I wrong. Is there a better/cleaner approach?
#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);
Any other way to count and get a total (not a sum, a total of inputted numbers)?
I've been trying to figure this out for days. Obviously, I am a beginner and I would love to understand. I have checked about 5 php books and the php online manual. I would appreciate if anyone could lead me in the right direction. Please :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将执行您所要求的操作。它将数字分割成一个数组,使用 array_sum 计算所有元素的数量,然后使用数组的大小计算元素的总数。它还使用修剪来清理用户可能输入的任何空白。
您可以在此处查看此代码的实际运行情况。
This will do what you are requesting. It splits the numbers into an array, uses array_sum to count up all the elements and then uses the size of the array to count the total number of elements. It also uses trim, to clean up any whitespace a user may have entered.
You can see this code in action here.