How can I add all of my array values together in PHP?

前端 未结 4 1676
遇见更好的自我
遇见更好的自我 2020-11-27 08:46

How can I add all of my array values together in PHP? Is there a function for this?

4条回答
  •  隐瞒了意图╮
    2020-11-27 09:03

    If your array consists of numbers, you can use array_sum to calculate a total. Example from the manual:

    $a = array(2, 4, 6, 8);
    echo "sum(a) = " . array_sum($a) . "\n";
    

    If your array consists of strings, you can use implode:

    implode(",", $array);
    

    it would turn an array like this:

    strawberries
    peaches
    pears
    apples
    

    into a string like this:

    strawberries,peaches,pears,apples
    

提交回复
热议问题