计数和总计

发布于 2024-12-20 01:12:50 字数 872 浏览 4 评论 0原文

我有一个用户输入的数字列表。我想对它们进行计数并得到:

  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书籍和php在线手册。如果有人能引导我走向正确的方向,我将不胜感激。请 :)

I have a list of numbers that are inputted by users. I want to count them and get:

  1. Subtotals for each number (only numbers possible are 1, 2, 3, 4, 5), and
  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空名 2024-12-27 01:12:50

这将执行您所要求的操作。它将数字分割成一个数组,使用 array_sum 计算所有元素的数量,然后使用数组的大小计算元素的总数。它还使用修剪来清理用户可能输入的任何空白。

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

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

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.

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

You can see this code in action here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文