PHP: How to Get the Last Character of a String CodeUnit 19 OCT 2011

To get the last character of a given string in PHP is made very, very simple thanks to the plain old vanilla substring (substr) function.

When you call substr, you feed it the string, the starting point and the number of characters you want it to return. If you leave out the number of characters to return, then the function returns all the characters from the starting point until the end of the string.

Knowing this, we can then figure out that if we want the last character of a string, we simply make the starting point the length of the string minus 1 to take into account the zero-based character position counter. In practice:

echo substr('My String',strlen('My String') - 1); //returns g

However, substr makes this EVEN easier by allowing us to specify a NEGATIVE starting point. This indicates that the function should count towards the left starting from the last character instead of the usual counting to the right starting from the first character. Armed with this knowledge, our call to retrieve the last character in the string now becomes:

echo substr('My String',-1); //returns g

Feeding a -3 would return the last three characters of the string, meaning our above example would print out ‘ing’.

And now you know! :)

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.