未初始化的字符串偏移量php

时间:2019-03-20 23:58:38

标签: php string initialization offset notice

我正在用PHP编写自己的计算器。

我的代码有问题,因为我不知道我试图在字符串中读取的位置过多。所以,如果有人能启发我..

我得到的确切错误是:

  

PHP注意:未初始化的字符串偏移量:第76行/home/salim/Bureau/web/piscine_php/d01/ex11/do_op_2.php中的4

这是下面的代码:

function decoupe ($argv)
{
global $nbr1;
global $nbr2;
global $sign;
$string = NULL;
$string = trim($argv[1], " \t");
echo $string;
echo "\n";
$x = 0;
while($string[$x]) 
{
    if (is_numeric($string[0]) == false)
        error_msg();
    if (is_numeric($string[$x]) && $string[$x + 1])
    {
        while (is_numeric($string[$x]))
        {
            $nbr1 .= $string[$x];
            $x++;
        }
    }
    if (is_thisoperator(substr($string, $x)))
    {
        $sign .= $string[$x];
        $x++;
    }
    else
    {
        error_msg();
    }

    if ($string[$x + 1] && is_numeric($string[$x]))
    {
        while (is_numeric($string[$x]))
        {
            $nbr2 .= $string[$x];
            $x++;
        }
    }
    else
    {
        error_msg();
    }
}

1 个答案:

答案 0 :(得分:1)

请勿使用$string[$x]作为测试$x是否为字符串中有效索引的方法。当$x在字符串之外时,它将显示警告。请改用$x < strlen($string)。所以改变:

while ($string[$x])

while ($x < strlen($string))

并更改

if ($string[$x + 1] && is_numeric($string[$x]))

if ($x + 1 < strlen($string) && is_numeric($string[$x]))
相关问题