Hello, Let's stay I have an array with only numbers. How can I add them up so I have them in one variable. So like I can have: $total_value_of_array Thank You!
<?php $numArray = array(1,2,3,4,5,6); $total_value_of_array = ""; foreach($numArray as $x) { $total_value_of_array.=$x; } echo ($total_value_of_array); ?> PHP:
that does not do anything, it just lists numbers 1 through 6. also, what if i did not no the number of numbers there were going to be, not just a set number of keys
I dont understand you... You have an array of numbers. By foreach you get all your array variables in one variable. If you want sum of this variables: <?php $numArray = array(1,2,3,4,5,6); $total_value_of_array = 0; foreach($numArray as $x) { $total_value_of_array+=$x; } echo ($total_value_of_array); ?> PHP:
You can also use these alternatives: $ar = array(3,4,6,2,6,4,24,3,34,32,19); // #1 - join $str1 = join('.', $ar); // split('.', $ar) to decode back to array // #2 - serialize $str2 = serialize($ar); // unserialize($str2) to decode // #3 - json $str3 = json_encode($ar); // json_decode($str3) to decode Code (markup):
Would be so much easier if you just did this. $sum = array_sum($array_name); the function array_sum calculates the sum of all the values in an array. All this splitting, looping etc is a waste of lines.