未初始化的字符串偏移php

问题描述 投票:0回答:1

我在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();
    }
}
php string initialization offset notice
1个回答
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]))
© www.soinside.com 2019 - 2024. All rights reserved.