PHP

How to Get the Last Character of a String in PHP1 min read

In this post, we’ll show you how to easily retrieve the last character of a string in PHP. There are multiple ways to achieve this, and we’ll explore three different methods.

Solution 1: Using the substr() Function

The substr() function in PHP is commonly used to extract a part of a string. You can specify the starting point and the length to extract the substring. To get the last character, we use the length of the string minus one as the starting position.

Example:




Explanation:

  • strlen($str) gives the length of the string.
  • substr($str, strlen($str) - 1) extracts the character starting from the last position.

Output:

Solution 2: Using the mb_substr() Function

If you are working with multi-byte characters (e.g., UTF-8 characters), the mb_substr() function is a better choice. This function safely handles multi-byte characters, unlike substr() which may not work well with characters like emoji or certain international characters.

Example:

Explanation:

  • The mb_substr() function takes a negative index to count from the end of the string.
  • Here, -1 tells mb_substr() to return the last character of the string.

Output:

Conclusion

These two solutions provide effective ways to retrieve the last character of a string in PHP:

  1. substr(): Use it when working with regular strings.
  2. mb_substr(): Use it when dealing with multi-byte or UTF-8 characters to ensure proper handling.

Both methods are quick and efficient depending on your needs. If you’re dealing with special characters, it’s safer to go with mb_substr().

1 Comment

Leave a Comment