简体   繁体   中英

Does treating a string as a character array return an “Uninitialized string offset” notice?

I'm getting the following notice

Notice: Uninitialized string offset: 1 in /script.php on line 17

Here are lines 16 and 17

$results = exec('ping -c 1 -w 1 ' . $ip, $output);
$servers[] = ($results[1] === '' ? false : true);

Is this being caused by me using $results[1] to get the second character of $results? If so, reading on the internet, it appears $string[] is recommended over substr() so why does it generate a notice?

My script relies on this file to generate JSON, so a notice breaks it (and this is an issues since it's an open source script)

exec returns a string. To access each character in the string you can use the array notation $string[x] like $string[1] starting from 0 . However, if there are 0 or 1 characters then [1] doesn't exist. It appears you are just checking the string as you are checking '' . Use one of the following:

$servers[] = $results ? true : false;
//or
$servers[] = ($results === '') ? true : false;

Based on your comment, to check for the character position and a space:

$servers[] = (isset($results[1]) && $results[1] === ' ') ? false : true;
//or
$servers[] = (strpos($results, ' ') === 1) ? false : true;

I would use strpos .

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