Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php error reporting Uninitialized string offset: 0

i am doing a stuff in php and not it is debug mode. So i am us

error_reporting(E_ALL);

but When i try to access any character of string it gives me error due to the error reporting.

$sentence = "Hello World"; 
$sentence[0]   //Uninitialized string offset: 0

edited:

public static function prepareSentence($sentence)
{
    $sentence = trim($sentence);
    if ($sentence[0] == '"')  //Uninitialized string offset: 0 
        $sentence = substr($sentence, 1, strlen($sentence));

    if ($sentence[strlen($sentence) - 1] == '"')
        $sentence = substr($sentence, 0, -1);

    if ($sentence[0] == '"' || $sentence[strlen($sentence) - 1] == '"')
        return self::prepareSentence($sentence);
    return $sentence;
}

How should I do in order to work in dev mode. I need the error_reporting(E_ALL);

thanks in advance.

like image 728
Elbek Avatar asked Feb 04 '12 05:02

Elbek


2 Answers

For empty string, you can't use $sentence[0], that will cause the notice you got.

You can add !empty($sentence) to check if it is empty.

like image 76
xdazz Avatar answered Sep 20 '22 14:09

xdazz


You are creating $sentence as a string ($sentence = "Hello World";) and then calling it as an array ($sentence[0]). That is no longer allowed. It used to work silently in the background and change the variable to an array for you with that error but as of PHP 7.1 it will fail completely. Comes out as an E_NOTICE error (should actually be upgraded to E_DEPRECATED or something as it now fails but whatever).

like image 42
Sean Avatar answered Sep 19 '22 14:09

Sean