This is a short tutorial on how to get the last character of a string in PHP. There are three simple ways to go about doing this. However, we recommend that you use the last example.
Treat the string like an array.
The first method uses the array approach.
Here, we will treat the string like an array of characters.
//Our example string. $string = 'This is a string'; //Get the length of the string. $length = strlen($string); //Get the array index of the last character. $index = $length - 1; //Print out the last character. echo $string[$index];
In the code above, we get the length of the string in order to determine the array index of the last character. We then subtract 1 from the length because array indexes start at 0.
Now obviously, the example above is a little too verbose. In other words, we do not need to write four separate lines of code for a relatively simple operation.
However, we can shorten this down pretty easily.
//Our example string. $string = 'This is a string'; //Print out the last character. echo $string[strlen($string) - 1];
Using substr to get the last character of a string in PHP.
The second method uses PHP’s inbuilt substr function.
//Our example string. $string = 'This is a string'; //Use PHP's substr function. echo substr($string, -1);
As you can see, we passed -1 in as the second parameter.
Personally, I prefer the substr method, simply because it involves less code. It also avoids the possibility that another developer will come along and assume that $string is an actual array.
Getting the last character when a string has “special characters”.
If there is a possibility that your string will contain special characters, then you will need to use the mb_substr function instead. This is because PHP’s mb_substr function is “multi-byte safe”.
Otherwise, you may end up with garbled characters.
//The string, which contains a special character at the end. $test = 'Helloä'; //Get the last character using mb_substr $lastChar = mb_substr($test, -1); //var_dump it out var_dump($lastChar);
If you run the example above, you will see that we are able to get the last character even though it is an umlaut.