artoak Posted August 17, 2009 Share Posted August 17, 2009 I am summing elements from 1 array to another array using some code that is independent of array length. In the example here the answer is correct but I'm still getting these non fatal errors. I'm presuming the error is to do with setting the array key but since my arrays are of variable length, I cannot figure out how to set this 'key' attribute. Any ideas would be greatly appreciated. Notice: Undefined offset: 0 in /home/www/... on line 29 Notice: Undefined offset: 1 in /home/www/... on line 29 36 49 <?php $year = array(0 => 21, 1 => 28); $ydata = array(0 => 15, 1 => 21); // prints an element function myPrint($value) { print "$value "; } //add every element of 1 array with matching element of different array $sum_array = array_sum_values($year, $ydata); array_walk($sum_array, "myPrint"); function array_sum_values() { $return = array(); $arrArgs = func_get_args(); foreach($arrArgs as $arrItem) { foreach($arrItem as $k => $v) { $return[$k] += $v; //***Line 29*** } } return $return; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/170712-solved-error-undefined-offset-when-summing-elements-from-1-array-to-another-array/ Share on other sites More sharing options...
genericnumber1 Posted August 17, 2009 Share Posted August 17, 2009 The simplest way would just be to set it if it's not set... so the loops become <?php foreach($arrArgs as $arrItem) { foreach($arrItem as $k => $v) { if(!isset($return[$k])) { $return[$k] = 0; } $return[$k] += $v; } } ?> Obviously I didn't check your logic since you said your answer was correct. Quote Link to comment https://forums.phpfreaks.com/topic/170712-solved-error-undefined-offset-when-summing-elements-from-1-array-to-another-array/#findComment-900367 Share on other sites More sharing options...
artoak Posted August 17, 2009 Author Share Posted August 17, 2009 Thank you very much. Your solution is elegant and clearly what appears logical to me, often isn't. I continue my learning curve. Quote Link to comment https://forums.phpfreaks.com/topic/170712-solved-error-undefined-offset-when-summing-elements-from-1-array-to-another-array/#findComment-900515 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.