How to get the last character of a string using PHP

22 March 2023 426 Reading time: 1 minute

Getting the last character of a string is pretty easy with PHP. You can use the substr() function in PHP to do this.

The substr() function lets you cut a specific part of a string and return the rest. When the second parameter of this function is a negative integer, it takes the specified number of characters from the end of the array.

The following is sample code for using the substr() function to get the last character of a string:

$text = "This is sample text";
$last_character = substr($text, -1);
echo "Last charcter: " . $last_character;

This code is "This is sample text" defined in the $text variable. It uses the substr() function to get the last character of the string. The function takes the last character (-1) of the $text variable and assigns it to the $last_character variable. Finally, the last character in the $last_character variable is printed using the echo statement.

Using another method, you can get the last character of any string (word, sentence). You can use the code sample below

Aşağıda kod örneğini kullana bilirsiniz

 

$text = "This is sample text";
$last_character = $text[-1];
echo "Last charcter: " . $last_character;

Similar articles