Php 多行上未定义的偏移量

Php 多行上未定义的偏移量,php,Php,我写了一个解决数学问题的小程序。但当我运行时,它在第9,11,13,15行给出了一个未定义的偏移量错误。 我搜索了各种各样的问题,但没有找到任何有用的。 这可能是什么原因造成的 <?php $arr = [1,3,5,7,9,11,13,15]; $tries=0; $answer=0; while(($answer!=30) && ($tries!=1000)) { $tries = $tries+1; $num1=getRandomNumber();

我写了一个解决数学问题的小程序。但当我运行时,它在第9,11,13,15行给出了一个未定义的偏移量错误。 我搜索了各种各样的问题,但没有找到任何有用的。 这可能是什么原因造成的

<?php
$arr = [1,3,5,7,9,11,13,15];
$tries=0;
$answer=0;
while(($answer!=30) && ($tries!=1000))
{
    $tries = $tries+1;
    $num1=getRandomNumber();
    $num2=getRandomNumber();
    $num3=getRandomNumber();
    $num4=getRandomNumber();
    $num5=getRandomNumber();
    if($num5 + $num4 + $num3 + $num2 + $num1 == 30)
    {
        $answer = 30;
        echo $num1 + "+"  + $num2 + "+" + $num3 + "+" + $num4 + "+" + $num5 + " = 30";
        break;
    }
}
if($tries==1000)
{
    echo "1000 tries completed";
}


function getRandomNumber()
{
    $arr = [1,3,5,7,9,11,13,15];
    $r = mt_rand(1,15);
    if(($r%2)!=0)
    {
        return $arr[$r];
    }
}
?>

您应该更改行:

$r = mt_rand(1,15);
进入


因为
getRandomNumber
函数中的
$arr
只有8个元素(不是16个)

您应该更改行:

$r = mt_rand(1,15);
进入


由于
getRandomNumber
函数中的
$arr
只有8个元素(不是16个)

getRandomNumber()
函数中,您正在生成
1
15
之间的数组索引,但数组的长度只有
8个
元素

要解决此问题,请更新对
mt_rand()
的调用以支持实际阵列大小:

$r = mt_rand(0, count($arr) - 1);

旁注(不是特定于答案),PHP中的字符串连接是用句点
完成的,而不是
+

echo $num1 + "+"  + $num2 + "+" + $num3 + "+" + $num4 + "+" + $num5 + " = 30";
// should be:
echo $num1 . "+"  . $num2 . "+" . $num3 . "+" . $num4 . "+" . $num5 . " = 30";

getRandomNumber()
函数中,您正在
1
15
之间生成一个数组索引,但数组的长度只有
8
个元素

要解决此问题,请更新对
mt_rand()
的调用以支持实际阵列大小:

$r = mt_rand(0, count($arr) - 1);

旁注(不是特定于答案),PHP中的字符串连接是用句点
完成的,而不是
+

echo $num1 + "+"  + $num2 + "+" + $num3 + "+" + $num4 + "+" + $num5 + " = 30";
// should be:
echo $num1 . "+"  . $num2 . "+" . $num3 . "+" . $num4 . "+" . $num5 . " = 30";
mt_rand
函数返回的数字高于数组索引开关7。您可以扩展数组并使其具有16个索引,也可以将
mt_rand
函数中的范围减小到0-7


mt_rand
函数返回的数字高于数组索引开关7。您可以扩展数组并使其具有16个索引,也可以将
mt_rand
函数中的范围缩小到0-7。

您的数组中有8个数字,因此索引为0->7,但您正在生成随机索引1->15。啊!这是我这边的一个愚蠢的错误。我会修好的。你的数组中有8个数字,所以索引0->7,但你正在生成随机索引1->15。啊!这是我这边的一个愚蠢的错误。我会修好的。啊!我对java和php之间的连接感到困惑。啊!我对java和php之间的连接感到困惑。