Array Undefined index error (notice) in PHP

Alex picture Alex · Apr 20, 2010 · Viewed 10.3k times · Source

I have this function:

function coin_matrix($test, $revs) {
    $coin = array();

    for ($i = 0; $i < count($test); $i++) {
        foreach ($revs as $j => $rev) {
            foreach ($revs as $k => $rev) {
            if ($j != $k && 
                $test[$i][$j] != null && 
                $test[$i][$k] != null) {

                $coin[$test[$i][$j]][$test[$i][$k]] += 1 / ($some_var - 1);
                }
            }
        }
    }
    return $coin;
}

where

$test = array(
array('3'=>'1','5'=>'1'),
array('3'=>'2','5'=>'2'),
array('3'=>'1','5'=>'2'),
array('3'=>'1','5'=>'1'));

and

$revs = array('3'=>'A','5'=>'B');

the problem is that when I run it, it returns these errors (notices):

Notice: Undefined index: 1 at line 10

Notice: Undefined index: 1 at line 10

Notice: Undefined index: 2 at line 10

Notice: Undefined index: 2 at line 10

Notice: Undefined index: 2 at line 10

Notice: Undefined index: 1 at line 10

which is this line: $coin[$test[$i][$j]][$test[$i][$k]] += 1 / ($some_var - 1);

The problem is that at the end the function returns the correct matrix (array) and if I test to see if $coin[$test[$i][$j]][$test[$i][$k]] exists, then it doesn't return it anymore.

Any suggestion is greatly appreciated!

Thanks!

Answer

Powerlord picture Powerlord · Apr 20, 2010
$coin[$test[$i][$j]][$test[$i][$k]] += 1 / ($some_var - 1);

The warning is being generated by the +=. += needs to look up the element before adding to it, and you haven't initialized any of the elements in $coin the first time you access them.