0 0 Votes

PHP: Cut out last Character from String

Question by Guest | 18/04/2015 at 17:14

It would like to read out the last character from a string using PHP. For example, when I have the string "abc", I would like to get the character "c".

Is there any simple PHP function to do something like that? Perhaps, I have to mention that the length of the string is arbitrary and the last character can be both, a letters as well as a number.


Stefan Trost

Show Profile | Message
0Best Answer
0 Votes

You can use the function substr().

Here is a small example for the application.

$s = "abc"

echo substr($s, -1, 1);  // c

As you can see, we are starting with the string "abc" and we are getting the last character, that is "c". As a first parameter, we are passing the string we would like to process to substr(). After that, the starting position and then the number of characters that should be read out. Because we would like to count the start position from behind, we are using a negative value.

By the way, in this case, we can omit the third parameter and nevertheless we are getting the same result:

$s = "abc"

echo substr($s, -1);  // c

The reason is that if the third parameter is missing, substr() is returning the entire remaining string starting from the given start position. And if we are using -1 as starting position, in each case, the remaining string is exactly one character in length - which is the last character of our string we are searching for.
18/04/2015 at 22:26

ReplyPositive Negative

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own articles on askingbox.com. How to do.