Friday, October 10, 2025
HomeLanguagesHow to get the last character of a string in PHP ?

How to get the last character of a string in PHP ?

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




<?php
 $txt = "Geeksforneveropen";
 echo "Last Character of string is : " 
   .$txt[strlen($txt)-1];
?>


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




<?php
$txt = "Akshit Loves GeeksForGeeks";
echo "Last character of String is : "
  .substr($txt, strlen($txt)-1);
?>


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




<?php
$txt = "Akshit Loves GeeksForGeeks";
echo "Last character of String is: ".substr($txt, -1);
?>


Output

Last character of String is: s

NOTE: If you’re using multibyte character encodings like UTF-8, use mb_substr() instead of substr .

RELATED ARTICLES

Most Popular

Dominic
32349 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6717 POSTS0 COMMENTS
Nicole Veronica
11880 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6838 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6792 POSTS0 COMMENTS