EnglishAdam
EnglishAdam

Reputation: 1390

Undefined offset when creating/adding Multi-Dimensional array values

I am adding to an array on the fly, using code similar to this;

 $arrayF[$f+1][$y][$x+1] = $value+1;

But I receive this in the error report:

Undefined offset: 1

QUESTION: Why do I get an undefined offset when I am trying to CREATE an array value?

What can I do about it?

Further info, if relevant: It occurs in a loop as so, where I am 'sprawling' through a masterArray

if (is_array($arrayF[$f])){ 
    foreach ($arrayF[$f] as  $key2 => $arrayF2) {
        $y = $key2;
        foreach ($arrayF2 as $key3 =>$value) {
            $x = $key3;
            if (($y<=100)&& ($y>=1)&&($x<=100)&&($x>=1)){
                if ($value < $arrayMaster[$y][$x])  {
                    $arrayMaster[$y][$x] = $value;//resets value in a master array
                    $arrayF[$f+1][$y][$x+1] = $value+1;//creates a new array for F to 'sprawl' with
                    $max = $f+1;
                }
            }
        }
    }
}

Upvotes: 1

Views: 1676

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

Simple, because when you do this: $arrayF[$f+1][$y][$x+1] = $value+1;, you can't be sure that $arrayF[$f+1] is a valid offset/index/key. All you know for sure is that is_array($arrayF[$f]) is true.

The fix is rather simple:

if (!isset($arrayF[$f+1]) || !is_array($arrayF[$f+1])) {
    $arrayF[$f+1] = array(
        $y => array()
    );
} else if (!is_array($arrayF[$f+1][$y])) {
        $arrayF[$f+1][$y] = array();
}
$arrayF[$f+1][$y][$x+1] = $value+1;

Now why are you getting the notice? That's because, if $arrayF[$f+1] doesn't exist, PHP will happily create it for you when you do a simple assignment like $arrayF[$f+1] = 'foobar';. However, you're accessing a (possibly) non-existent offset (which would evaluate to null), and try to use it as an array: $arrayF[$f+1][$y], if $arrayF[$f+1] doesn't exist, there can't be a $y index in there, hence the notice: PHP is warning you about a possible bug in your code

Update:
As discussed in the comments below: is_array can produce an undefined offset notice, seeing as it assumes that the argument you pass to it actually exists. To avoid such notices from being produced, an isset check is required, so I've updated the code above accordingly.

Upvotes: 2

Related Questions