How to get the last character of a string in PHP ? (original) (raw)
Last Updated : 07 Aug, 2024
In this article, we will find the last character of a string in PHP. The last character can be found using the following methods.
**Using **array() Method: In this method, we will find the length of the string, then print the value of (length-1). For example, if the string is "Akshit" Its length is 6, in zero-indexing, the value of (length-1) is 5 which is the character "t" The length can be found using the PHP**strlen() method.
The strlen() is a built-in function in PHP which returns the length of a given string. It takes a string as a parameter and returns its length. It calculates the length of the string including all the whitespaces and special characters.
**Syntax:
strlen($string)
**Example:
PHP `
`
**Output:
Last Character of string is : s
**Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string.
**Syntax:
substr(string_name, start_position, string_length_to_cut)
**Example: For example, if the string is "Akshit loves GeeksForGeeks". The last character of the string is "s". There are 2 ways to reach "s". From the beginning "s" is at the 25th position. We can find the length of the string, then display "length-1". This means we want to display part of the string using substr() method where the starting point is "length-1".
PHP `
`
**Output: From the end, "s" is at 1st position. We can display string from (-1)
Last character of String is : s
**From end: "s" is at 1st position
We can display string from "-1"
PHP `
`
Output
Last character of String is: s
Using mb_substr() Method
The mb_substr() function is used to extract a part of a string with multibyte character support. It is part of the mbstring extension, which is essential for handling multibyte character encodings such as UTF-8.
**Example: For instance, if the string is "Akshit Loves GeeksForGeeks", the last character of the string is "s".
PHP `
`
Output
Last character of String is: s
**NOTE: If you’re using multibyte character encodings like UTF-8, use **mb_substr() instead of substr .