Tapha
Tapha

Reputation: 1511

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

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

Upvotes: 2

Views: 2327

Answers (4)

Vinit Kadkol
Vinit Kadkol

Reputation: 1285

Let the given array values may contain integer or may not be. It would be better to have check and filter the values.

$array = array(-5, "  ", 2, NULL, 13, "", 7, "\n", 4, "\t",  -2, "\t",  -8);

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values

$result = array_filter( $array, 'is_numeric' );
echo array_sum($result);

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342629

if your array are all numbers and you want to add them up, use array_sum(). If not, you can use implode()

Upvotes: 2

Arnkrishn
Arnkrishn

Reputation: 30442

array_sum function should help. Here I presume your array comprises of integer or float values.

Upvotes: 1

Pekka
Pekka

Reputation: 449613

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

Upvotes: 13

Related Questions