简体   繁体   中英

I am getting error while calculating the length of a string

I am trying to calculate the length of a string without using library function(for learning purpose). I am using the following code:

<?php 
$name = "Mohammad Umar";
$i=0;
while($name[$i] != ''){
    $i++;
}
echo $i++;
?>

But I am getting error like this:

Notice: Uninitialized string offset: 13 in C:\\xampp\\htdocs\\form\\test.php on line 4

I have already initialized $i, then why it is saying Uninitialized string offset? Is there a better way to calculate the length of a string without library function, please suggest me.

Without using the strlen function you could do this

$name = "Mohammad Umar";
$i=0;
while(isset($name[$i])){
    $i++;
}

You can use str_split to split the string to an array and count it.

$name = "Mohammad Umar";
$arr = str_split ($name);
echo count($arr);

https://3v4l.org/OIDlt#output

Another solution would be to do a regex /.+/ and count the output array. But that is just plain S....
But it would work.

You could simply use php's strlen function

<?php 
$name = "Mohammad Umar";
echo strlen($name);
?>

You are receiving the error because the code you've written checks for $name[13] this part however does not exist. you can go from [0] to [12] .

edit

Just read you can't use strlen

then why not check if it exists

while(isset($name[$i]){
    $i++;
}

2 more ways: both functions use substr() , the first utilises a while() loop and the second is recursive

function stringLen1($string)
{
    $result = 0;
    while ($string != '') { // note: loose typing
        $string = substr($string,1);
        $result++;
    }
    return $result;
}

function stringLen2($string)
{
    if ($string == '') { // note: loose typing
        $result = 0;
    } else {
        $result = stringLen2(substr($string,1)) + 1;
    }
    return $result;
}

$name = "Mohammad Umar";
echo stringLen1($name)."<br />\n";

echo stringLen2($name)."<br />\n";

A for loop can also work for this.

for ($i = 0; isset($name[$i]); $i++);

echo $i;

To address your question:

"I have already initialized $i, then why it is saying Uninitialized string offset?"

It doesn't mean that the variable $i is uninitialized. It means that the value of $i (13) is an uninitialized offset of $name .

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