Search code examples
phpstringinitializationoffsetnotice

Uninitialized string offset php


I am writting my own calculator on PHP.

I have a problem with my code because i don't know where i am trying to read too far in the string. So if anyone can enlighten me ..

The exact error i get is :

PHP Notice: Uninitialized string offset: 4 in /home/salim/Bureau/web/piscine_php/d01/ex11/do_op_2.php on line 76

Here is the code below :

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();
    }
}

Solution

  • Don't use $string[$x] as a way to test whether $x is a valid index in the string. It prints a warning when $x is outside the string. Use $x < strlen($string) instead. So change:

    while ($string[$x])
    

    to

    while ($x < strlen($string))
    

    and change

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

    to

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