gpt4 book ai didi

php - 计数和总计

转载 作者:行者123 更新时间:2023-12-04 06:05:28 25 4
gpt4 key购买 nike

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

  • 每个数字的小计(只有可能的数字是 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 在线手册。如果有人能引导我走向正确的方向,我将不胜感激。请 :)

    最佳答案

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

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

    您可以在操作中看到此代码 here .

    关于php - 计数和总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408967/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com