Hi All, I have a list of about 10 variables. Each variable is stored as "0,0,0,0,0,0,0,0" What is the most efficient way to add them together vertically? 0,0,0,0,0,0,0,0 2,2,0,0,0,0,0,0 1,0,1,0,0,0,0,0 = 3,3,1,0,0,0,0,0 Thanks!
Shouldn't the answer in your demo be "3,2,1,0,0,0,0,0"? To achieve this you can break the variables into arrays. <?php $string1 = "0,0,0,0,0,0,0,0"; $string2 = "2,2,0,0,0,0,0,0"; $string3 = "1,0,1,0,0,0,0,0"; $array1 = explode(",", $string1); $array2 = explode(",", $string2); $array3 = explode(",", $string3); for ($i=0; $i<8; $i++) { $total = $array1[$i] + $array2[$i] + $array3[$i]; if ($i == 7) { $display .= "$total"; } else { $display .= "$total, "; } } echo ("$display"); ?> PHP:
Theirs no need to loop (seeing as your not using arrays, or atleast it seems like that): echo str_replace(',', NULL, '0,0,0,0,0,0,0,0') + str_replace(',', NULL, '2,2,0,0,0,0,0,0') + str_replace(',', NULL, '1,0,1,0,0,0,0,0'); PHP: Just replace the third paremeter on all the str_replace()'s with the corresponding variable.
If you store he strings in an array, than this code will do the job, with as many strings as you like: <?php $strings[1] = "0,0,0,0,0,0,0,0"; $strings[2] = "2,2,0,0,0,0,0,0"; $strings[3] = "1,0,1,0,0,0,0,0"; $nr=array(); foreach($strings as $string) { $foo=explode(',',$string); foreach($foo as $key=>$value) @$nr[$key]+=(int)$value; } $result=implode(",",$nr); print_r($result); // 3,2,1,0,0,0,0,0 PHP:
If you want efficiency, the first thing you need to do is determine all possible combinations of values so you can start thinking about optimizations before you start writing code. If you write code first, you're going to try and account for every case just like all programmers do. In your title, you're adding an element with 5 digits with another that has 6 digits. In your post, everything seems to use 8 digits though. Do your strings really have a variable number of digits, or was the title a typo? All of the examples you've posted have single number digits, is there any chance of your strings having 2+ number digits? (1,23,45,678,9,0) Assuming every string will be a single numbers, eight digit long string, and that your "list" is actually an array, I would start with this. <?php $list = array( '0,0,0,0,0,0,0,0', '2,2,0,0,0,0,0,0', '1,0,1,0,0,0,0,0' ); $sums = array(0,0,0,0,0,0,0,0); for($i = count($list) - 1; $i > -1; $i--) { $sums[0] += $list[$i][0]; $sums[1] += $list[$i][2]; $sums[2] += $list[$i][4]; $sums[3] += $list[$i][6]; $sums[4] += $list[$i][8]; $sums[5] += $list[$i][10]; $sums[6] += $list[$i][12]; $sums[7] += $list[$i][14]; } echo implode(',', $sums), PHP_EOL; ?> PHP: