Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Whant to remove last character from string

Status
Not open for further replies.

timgerr

IS-IT--Management
Jan 22, 2004
364
US
Hello all,
Here is something goofy, I am trying to remove the last character from a string so I use this method:
Code:
$test = '012345678';
while($test){
  echo $test . '<br/>';
  $test = substr($test,0,-1);
}
This is the output
Code:
012345678
01234567
0123456
012345
01234
0123
012
01
it ends at 01. I want to recursively go through $test and get rid of the last character, what is the best way to do it?

Thanks for the read,
timgerr

-How important does a person have to be before they are considered assassinated instead of just murdered?
So there you go! You're the retarded offspring of five monkeys having butt sex with a fish-squirrel! Congratulations!


 
Code:
while (strlen($test) > 0){
  $test = substr($test, 0, -1);  
}
 
How about:

Code:
  $test = substr($test,(strlen($test) - 1),1));

Didn't test this code but the concept is good.




 
Your code is fine, its doing what its supposed to.

You are telling it to cycle through this while your variable exists or is true. the second it gets to 0 well your variable is just that 0 in essence False therefore it doesn't go in to the while loop the last time to echo out the value for it.

Your code would work if the first character was anything else other than 0. That fact that its zero is what throws it off. There no way to distinguish between a string 0 and a FALSE value they are both 0.


Try checking for the length of your variable instead:

Code:
while(strlen($test)>0){
  echo $test . '<br/>';
  $test = substr($test,0,-1);
}




----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Oops should have refreshed before posting.

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks all for the help, I have learned something.
timgerr

-How important does a person have to be before they are considered assassinated instead of just murdered?
Congratulations!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top