Jump to content

[SOLVED] Error 'Undefined offset:...' when summing elements from 1 array to another array


Recommended Posts

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;

}

?>

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.