doukong9316
2014-12-16 04:22 阅读 116
已采纳

为什么我收到Undefined Variable错误?

I know that it's not necessary to define variables and arrays before using them in PHP. But I'm facing 'Undefined Variable mat1' and 'Undefined Variable mat2' errors when I run the following code:

for($i=0;$i<3;$i++)
{
   for($j=0;$j<3;$j++)
   {
       $ans[$i][$j] = 0;
       for($k=0;$k<3;$k++) 
       {
          $ans[$i][$j] = $ans[$i][$j] + $mat1[$i][$k]*$mat2[$k][$j];
       }
   }
}
var_dump($ans);

I tried to define them with following 2 lines:

$mat1=array(array());
$mat2=array(array());

But errors were changed to 'Undefined offset: ...' errors. Am I missing something in my code?!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    doujiene2845 doujiene2845 2014-12-16 04:29

    Why I'm getting Undefined Variable errors?

    Because you haven't defined anything.

    Just use

    $mat1 = $mat2 = array(
                0 => array(
                        0 => 1, 
                        1 => 1, 
                        2 => 1, 
                        3 => 1, 
                        4 => 1, 
                        5 => 1, 
                    ),
                1 => array(
                        0 => 2, 
                        1 => 2, 
                        2 => 2, 
                        3 => 2, 
                        4 => 2, 
                        5 => 2, 
                        ),
                2 => array(
                        0 => 3, 
                        1 => 3, 
                        2 => 3, 
                        3 => 3, 
                        4 => 3, 
                        5 => 3, 
                )
        );
    

    And test it

    点赞 评论 复制链接分享
  • douwuying4709 douwuying4709 2014-12-16 04:27

    You still have to have data in order to use the arrays. If mat1 is just an empty array then trying to access $mat1[1] will give you that undefined offset error

    点赞 评论 复制链接分享
  • dongyuan1902 dongyuan1902 2014-12-16 04:31

    Arrays are different than normal variables so you need to define it and most importantly before accessing any index of an array it is necessary for the array to have values in it. Otherwise you will get undefined offset error.

    Anotherthing is that, instead of using $mat1=array(array()) you can simply define $mat1=array() this will work for multidimensional arrays also.

    So unless your array actually have values at those indexes (even if empty values), you will get undefined offset error.

    点赞 评论 复制链接分享

相关推荐