php error reporting Uninitialized string offset: 0

Elbek picture Elbek · Feb 4, 2012 · Viewed 45.9k times · Source

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.

Answer

xdazz picture xdazz · Feb 4, 2012

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.