12

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

6
  • 8
    Out of interest - why don't you want to use strlen? Encoding issues? Commented May 13, 2011 at 8:29
  • 6
    Its like "I want to eat cake but don't want to use Knife to cut it, is there any other way.....!!!!!" :) Commented May 13, 2011 at 8:34
  • The time taken by strlen function is proportional to the length of string. So yes, I like to see an alternate solution. Commented Nov 20, 2014 at 12:54
  • @Salman A: all current answers either use strlen internally or implement it, and are therefore also O(n). The only O(1) answer is to store it somewhere beforehand. Commented Jul 14, 2015 at 13:10
  • From the comments you've made it looks like you're obsessing over a micro-optimization. First off, this is almost certainly a waste of time because unless you're processing an utterly huge string or processing strings in a very tight loop the speed of strlen is a non-issue. If your script is slow then I suggest profiling it to find where the real problem is. Second, no solution you can come up by yourself will be faster than PHP strlen Commented Mar 30, 2017 at 8:26

25 Answers 25

14

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Bad code, will error out.
7
 $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.

3 Comments

While this answers the question, it would be much better with some explanation.
Will report a length of 1 for empty strings
@GordonM I have update the answer. Now for empty string it will return 0.
4

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?

Comments

3

Lets be silly

function stupidCheck($string)
{
    $count = 0;
    for($i=0; $i<66000; $i++)
    {
       if(@$string[$i] != "")$count++;
       else break;
    }
    return $count;
}

3 Comments

function string_count($string) { $cnt=1; $count = 0; for($i=0; $i<$cnt; $i++) { if(@$string[$i] != ""){ $count++; $cnt+=1;} else break; } return $count; }
@WesleyvanOpdorp I've modified function to make it more readable. There is no need of if else inside for loop. There is also no need to loop it 66000 times unnecessarily.
I'm assuming this is a joke given the use of @ which is known to be horribly slow.
3

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.
?>

Comments

2

The answer given by Vaibhav Jain will throw the following notice on the last index.

Notice: Uninitialized string offset

I would like to give an alternative for this:

<?php

$str = 'India';

$i = 0;
while(@$str[$i]) {
    $i++;
}

echo 'Length of ' . $str . ' is ' . $i . '.';

2 Comments

Can you explain, Why without using @ it is producing "Notice: Uninitialized string offset" and how @ is handling this problem ?
'@' is an error control operator used in PHP. When we prepend this to any expression, errors that might occur for that expression will be ignored.
2

In newer PHP versions, you can use null coalescing operator to achieve this.

<?php

$string = 'test';

for($i = 0; ($string[ $i] ?? false) !== false; ++$i);

echo $i;// outputs length of the string.

Online Demo

Comments

1

mb_strlen — Get string length

 $string ='test strlen check';
 print 'mb_strlen(): ' . mb_strlen( $string, 'utf8' ) . "\n\n";

synatx: int mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )

str - The string being checked for length.

encoding - The encoding parameter is the character encoding. If it is omitted, the internal character encoding value will be used.

1 Comment

your synatx is off :-)
0

You could also cheat with something like:

print strtok(substr(serialize($string), 2), ":");

Or this one is quite amusing:

print array_sum(count_chars($string));

Comments

0
function mystrlen($str)
{
    $i = 0;
    while ($str != '')
    {
        $str = substr($str, 1);
        $i++;
    }
    return $i;
}

Comments

0
function findStringLength($string) {
    $length = 0;
    $lastStringChar1 = '1';
    $lastStringChar2 = '2';

    $string1 = $string . $lastStringChar1;
    $string2 = $string . $lastStringChar2;

    while ($string1[$length] != $lastStringChar1 || $string2[$length] != $lastStringChar2) {
        $length++;
    }

    return $length;
}

Comments

0

You can use this code for finding string length without using strlen() function.

<?php
function stringlength($withoutstringlength)
{
    $n = 0;
    while(substr($withoutstringlength, $n, $n+1) != '')//General syntax substr(string,start,length)
    {
        $n++;
    }
    echo $n;
}
stringlength("i am a php dev");
?>

Comments

0

Try this:

function length($value){

    if(empty($value[1])) return 1;

    $n = 0;
    while(!empty($value[$n+1])){

        $n++;
    }

    return $n+1;
}

Comments

0

This doesn't use loops but may face the O(n) issue if strrpos uses strlen internally.

function length($str)
{
    return strrpos($str.'_', '_', -1);
}

Comments

0
function my_strlen($str)
{
    for($i=-1; isset($str[++$i]); );
    return $i;
}

echo my_strlen("q");

Comments

0
$str = "Hello World";
$count= 0;
while( isset($str[$count]) && $str[$count] ) {
    $count++;
}
echo $count;

OUTPUT: 11

Comments

0

Renverser un charactère sans Function

class StringFunction {

    public function strCount($string) {
        $cpt=0;
        //isset pour cacher l'erreur
        // Notice: Uninitialized string offset
        while(isset($string[$cpt])) {
            $cpt++;
        }

        return $cpt;
    }

    public function reverseChar($str) {

        //mes indexes
        $start = 0;
        $end = $this->strCount($str)-1;     

        //Si $start est inférieur à $end
        while ($start < $end) {
            //change position du charactère
            $temp = $str[$start];
            $str[$start] = $str[$end];
            $str[$end]   = $temp;

            $start++;
            $end--;
        }

        return $str;
    }
}

$string = "Bonjour";
$a = new StringFunction();

echo $string . "<br>";
echo $a->reverseChar($string);

1 Comment

Please write your answer in English, as Stack Overflow is an English site.
0

This code will help you when you don't want to use any inbuilt function of php. You can test this here also http://phptester.net/

<?php
$stings="Hello how are you?";
$ctr=0;
while(1){
    if(empty($stings[$ctr])){       
                break;
    }

    $ctr++;
}
echo $ctr;

1 Comment

isn't empty a build in function for php?
0
<?php
$str  = "aabccdab";
$i = 0;
$temp = array();
    while(isset($str[$i])){
        echo $str[$i];
        $count = 0;
        if(isset($temp[$str[$i]])){
            $temp[$str[$i]] = $temp[$str[$i]]+1;
        }else{
            $temp[$str[$i]] = 1;
        }
        $i++;
}
print_r($temp);
?>

Comments

0
<?php
$str = "hello world";
$i = 0;
while ($str[$i] >= 0) {
    $i++;
}
echo "string length is: $i";
?>

Comments

-1

It's going to be a heavy work for your server, but a way to handle it.

function($string){
  $c=0;
  while(true){
    if(!empty($string[$c])){
      $c=$c+1;
    } else {
      break; // Prevent errors with return.
    }
  }
  return $c;
}

Comments

-1
$str = "STRING";
$i=0; $count = 0;
while((isset($str{$i}) && $str{$i} != "")){
$i++; $count++;
}
print $count;

1 Comment

Instead of writing while((isset($str{$i}) && $str{$i} != "")){ $i++; $count++; } you can write while($str{$i} != ""){ $i++; $count++; if(!isset($str{$i})) break; } to make function more readable.
-1

This can also help -

$s = 'string';
$temp = str_split($s); // Convert a string to an array by each character

// if don't want the spaces
$temp = array_filter($temp); // remove empty values

echo count($temp); // count the number of element in array

Output

6

Comments

-1
<?php

$arr = array('vadapalanai','annanager','chennei','salem','coimbatore');

$min = $arr[0];

$max = $arr[0];

foreach($arr as $key => $val){
    if (strlen($min) > strlen($val)) {
        $min = $val ;
    }
    if(strlen($max) < strlen($val)){
        $max = $val;
    }
}   
echo "The shortest array length is : " .$min. " ".strlen($min);
echo "<br>";
echo "The longest array length is: " .$max. " ".strlen($max);

 ?>

Comments

-1
$str  = 'I am XYZ'  
$count = 0;
$i=0;
while (isset($str[$i])) {  
 $count = $i;
 $i++; 
}  
echo $count;

1 Comment

This answer was reviewed in the Low Quality Queue. Here are some guidelines for How do I write a good answer?. Code only answers are not considered good answers, and are likely to be downvoted and/or deleted because they are less useful to a community of learners. It's only obvious to you. Explain what it does, and how it's different / better than existing answers. From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.