简体   繁体   中英

Uninitialized string offset: -1 when referencing single string character with curly braces

I have this code:

$len = strlen($string);

if ($string{$len-1} == '-') {
    // Do stuff...
}

However I get the following NOTICE error:

Uninitialized string offset: -1

When I var_dump($len-1) the value I get:

int 3

When I var_dump($string) I get:

string 'bobo' (length=4)

So could anyone tell me why this is causing a NOTICE error?

To prevent notice add additional condition to if statement:

$len = strlen($string);

if ($len > 0 && $string{$len-1} == '-')
    // Do stuff...
}

or use substr function:

if (substr($string, -1) == '-') {
    // Do stuff...
}
$len = strlen($string);
if(isset($string{$len-1})){
if ($string{$len-1} == '-') {
// Do stuff...
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM