Question

i am using a class to make some calculations with matrices, in this case: Get the sum of each column.

The sum output is correct, and if I hide the notices, the problem is solved, but logically, i prefer the correction.

In PHP 5.3 I get some notices in this function:

Notice: Undefined offset: 0 
Notice: Undefined offset: 0 
Notice: Undefined offset: 1 

script

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                $this->sum[0][$j] += $number; //notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());

        return $the_sum;
    }

Matrix:

1     | 4

0.25  | 1



var_dump($this->numbers);
array
  0 => 
    array
      0 => int 1
      1 => float 4
  1 => 
    array
      0 => float 0.25
      1 => int 1

and

 $this->get_num_columns() // 2

Any idea to correct these notices ?

thanks

Was it helpful?

Solution

Yes, the notice occurs because there is no initial value in the variables you are adding numbers to. You should check if the number exists and initialize it before you add a number to it. (Note, this won't improve your result, but it is good practice to initialize variables).

function sum()
    {
        foreach($this->numbers as $i => $rows)
        {
            foreach($rows as $j => $number)
            {
                if (!isset($this->sum[0][$j])) $this->sum[0][$j] = 0;
                $this->sum[0][$j] += $number; //no notices here
            }
        }
        $the_sum = new matrix($this->sum, 1, $this->get_num_columns());

        return $the_sum;
    }

Unrelated Points to Consider

  • Proper naming standards dictate that class name should be capitalized, to differentiate them from functions. So you should name your class Matrix and not matrix.
  • If you get the chance, a much better solution would be to pre-fill your array with 0s. array_fill() does the job nicely.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top