Now I am dealing with PHP but I`ve stucked with a strange issue:
I am making a simple foo for string length:
function slen($str) {
$len;
for ( $len=0; $str[$len]; $len++ ) {
/* while tehre is a symbol in $str continue counting, old C metnod */
}
return (int)$len;
}
it`s on as a code, and outputs the length but it booms with an PHP warning message :
PHP Notice: Uninitialized string offset: 3 in /home/ilian/Desktop/SERVER/ex4.php on line 5
And on my line 5 is the for loop initialization. So I got that PHP might be confusing by not knowing what kind of variables it checks for TRUE in that array because it can be
“Array”, “HELLO”, “MESS”, 50 and length is 4 which is correct, but in the case I aam checking a simple string for length. Any easygoing explanation?
The problem is that at some point your condition (
$str[$len]) will try to access an offset beyond the end of the string. That’s your stopping condition, but that stopping condition throws the notice, since accessing an undefined offset is considered an error (and rightly so). You’ll need to check whether the offset exists usingisset($str[$len]), which does not throw a notice.