-3

How to find string length in php without using strlen()?the condition is to take value of a=b=c=2, for words containing these alphabets?

6
  • 1
    Let me ask you whats wrong with strlen().?If there is a built in function then why are you complicating the programming.? Commented Nov 7, 2013 at 10:12
  • 1
    possible duplicate of stackoverflow.com/questions/5989221/… Commented Nov 7, 2013 at 10:14
  • How will you not be thirsty without drinking liquids?? Commented Nov 7, 2013 at 10:15
  • I know its very easy by using strlen but i cant use it ,Because its my task . Commented Nov 7, 2013 at 10:15
  • so no answer was correct for you??? Commented Nov 7, 2013 at 22:36

5 Answers 5

1

Seems like an interviewer questioned you... Well you can use mb_strlen()

<?php
echo mb_strlen("Hello World");

(or)

Use this.. read it somewhere before on SO

<?php
echo array_sum(count_chars("Hello World"));
Sign up to request clarification or add additional context in comments.

Comments

1

it might help you... not tested...

   $s = 'string';
   $i=0;
    while ($s[$i] != '') {
      $i++;
    }
    print $i;

Comments

1

You can use mb_strlen(), it will process Unicode strings.

Or use this function:

function get_string_length($string) {
  $i = 0;

  while ($string{$i} != '') {
    $i++;
  }

  return $i;
}

echo get_string_length('aaaaa'); // will echo 5

8 Comments

put @ in while (@$string{$i} != '') then correct output.
No, thats wrong. I added there &
this1 needs @ ,infact i am not getting satisfactory answer that why put@ this
That function is working, and there is no reason to have there @
i checked it ... u r right , happy
|
0

The solution is to use mb_strlen(). strlen() is broken for Unicode strings, anyway.

Comments

-1
<?php
function mystrlen($str) {
     $count = 0;
     for ($i = 0; $i < 1000000; $i++) {
        if (@$str[$i] != "") {
            if (@$str[$i] == "a" || @$str[$i] == "b" || @$str[$i] == "c") {
                $count+=2;
            } else {
                $count++;
            }
        }
        else {
            break;
        }
    }
    return $count;
}

echo mystrlen("this is temporary but we made it complex");
?>

6 Comments

And what if string length is > 1000000??
this is not difficult, u can remove and extend this r infinte , if u want.. i took this as an example
how will you write infinite in for loop??
you can use while lopp for infinite purpose or put nothing in for loop for infinte looping
??? in my answer there is while loop... So then my answer is correct for you...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.