Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find string length in php with out using strlen()?

Tags:

string

php

How can you find the length of a string in php with out using strlen() ?

like image 489
mymotherland Avatar asked May 13 '11 08:05

mymotherland


4 Answers

Simply you can use the below code.

<?php
     $string="Vasim";
     $i=0;
     while(isset($string[$i]))
     {
        $i++;
     }
     echo $i;  // Here $i has length of string and the answer will be for this string is 5.
?>
like image 112
Vasim Raja Avatar answered Sep 21 '22 20:09

Vasim Raja


 $inputstring="abcd";
 $tmp = '';    $i = 0;

   while (isset($inputstring[$i])){
        $tmp .= $inputstring[$i];
        $i++;
    }

echo $i; //final string count
echo $tmp; // Read string

while - Iterate the string character 1 by 1

$i - gives the final count of string.

isset($inputstring[$i]) - check character exist(null) or not.

like image 25
Narayan Avatar answered Nov 16 '22 15:11

Narayan


I know this is a pretty old issue, but this piece of code worked for me.

$s = 'string';
$i=0;
while ($s[$i] != '') {
  $i++;
}
print $i;
like image 14
Vaibhav Jain Avatar answered Nov 16 '22 16:11

Vaibhav Jain


I guess there's the mb_strlen() function.

It's not strlen(), but it does the same job (with the added bonus of working with extended character sets).

If you really want to keep away from anything even related to strlen(), I guess you could do something like this:

$length = count(str_split($string));

I'm sure there's plenty of other ways to do it too. The real question is.... uh, why?

like image 4
Spudley Avatar answered Nov 16 '22 14:11

Spudley