Jump to content

working with String, variable.charAt(i);

- - - - -

  • Please log in to reply
4 replies to this topic

#1
VakhoQ

VakhoQ

    Programmer

  • Members
  • PipPipPipPip
  • 127 posts
This function is like the strrev():



function F($str){

 for($i=strlen($str); $i>=0; $i--){

  echo $str[$i];

  }

}


$str="hello";

F($str);


but there are some errors on this line: echo $str[$i];
Error: Uninitialized string offset.

what mistake do i have?.. its interesting...
GNU/Linux Is the Best.

#2
VakhoQ

VakhoQ

    Programmer

  • Members
  • PipPipPipPip
  • 127 posts
that's something like this:


Posted Image
GNU/Linux Is the Best.

#3
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
You're starting at index = strlen($str) but that index does not exist, the highest index is strlen($str)-1. Take for example the world "hi", then index0 stands for "h" and index1 stands for "i" but strlen("hi") is 2 (but index 2 itself is out of range). So that's the mistake, you did take 0 as initial index but strlen starts counting index0 as 1, in other words: the max. index would be the string length minus 1.


function F($str){ 

 for($i=strlen($str)-1; $i>=0; $i--){ 

  echo $str[$i]; 

  } 

} 


$str="hello"; 

F($str); 


^^.

#4
VakhoQ

VakhoQ

    Programmer

  • Members
  • PipPipPipPip
  • 127 posts

webcodez said:

You're starting at index = strlen($str) but that index does not exist, the highest index is strlen($str)-1. Take for example the world "hi", then index0 stands for "h" and index1 stands for "i" but strlen("hi") is 2 (but index 2 itself is out of range). So that's the mistake, you did take 0 as initial index but strlen starts counting index0 as 1, in other words: the max. index would be the string length minus 1.


function F($str){ 

 for($i=strlen($str)-1; $i>=0; $i--){ 

  echo $str[$i]; 

  } 

} 


$str="hello"; 

F($str); 


^^.


Oh, You are right! thanks a lot! :)
GNU/Linux Is the Best.

#5
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
You're welcome! I'm glad I could help :).




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users