Just a simple question here. I need to add all the values in an array together and i don't have a set ammount of values in my array. All the values in my array are numbers.
Is there a function to do this and if not could someone suggest some code or a way around this problem.
The 'normal' way:
$array=array(1,2,3,4); $total=0; for($i=0;$i<count($array));$i++) { $total+=$array[$i]; }; echo $total."\n";
The 'playing around' way:
$array=array(1,2,3,4); eval('$total='.implode('+',$array).';'); echo $total."\n";
OK, but you left out the sparse/associative array way:
$a['this'] = 1; ... $a['that'] = 77; ... $a['the_other_thing'] = 1776; ... $total = 0; foreach ($a as $item) { $total += $item; }
Indeed I did leave that out.
Note that in PHP, some associative arrays (like the ones generated by mysql_fetch_array()) contain both the numerical and the associative indexes, effectively storing all data twice in the same array.
Kirk's method will parse all entries in the array, so in some cases you could get doubled results.