Question
I need to get the last character of a string in PHP.
For example, if the input string is "testers", I want the result to be "s". How can I do this in PHP?
Short Answer
By the end of this page, you will understand how to access the last character of a string in PHP, which syntax is most common, how to handle empty strings safely, and when to use multibyte-safe functions for Unicode text.
Concept
In PHP, strings can be accessed by character position using square bracket syntax. Since positions are zero-based, the first character is at index 0, the second at index 1, and so on.
To get the last character, you need the position of the final character in the string. A common way is to calculate the length of the string and subtract 1.
$str = "testers";
$lastChar = $str[strlen($str) - 1];
echo $lastChar; // s
This matters because string processing is very common in programming. You may need the last character to:
- check whether a path ends with
/ - validate file extensions
- inspect punctuation
- format data before saving or displaying it
In modern PHP, another concise option is negative string offset syntax:
$str = "testers";
echo $str[-1]; // s
However, you still need to think about edge cases like an empty string.
Also, if your string contains multibyte characters such as accented letters or emoji, standard byte-based access may not behave as expected. In those cases, use multibyte string functions such as mb_substr().
Mental Model
Think of a string as a row of numbered boxes:
tis box0eis box1sis box2tis box3eis box4ris box5sis box6
To get the last box, you can:
- count how many boxes there are
- move back one position
So if the string length is 7, the last character is at position 6.
Negative offsets are like saying, "start from the end instead of the beginning":
-1means the last character-2means the second-to-last character
Syntax and Examples
The most common ways to get the last character of a string in PHP are:
1. Using strlen() and string indexing
$str = "testers";
$lastChar = $str[strlen($str) - 1];
echo $lastChar; // s
How it works
strlen($str)returns the number of characters in the string- 1gives the index of the last character$str[...]accesses that character
2. Using negative offset syntax
$str = "testers";
echo $str[-1]; // s
This is shorter and easier to read, but it requires a PHP version that supports negative string offsets.
3. Using substr()
$str = ;
= (, -);
;
Step by Step Execution
Consider this code:
$str = "testers";
$lastChar = $str[strlen($str) - 1];
echo $lastChar;
Here is what happens step by step:
-
$str = "testers";- The variable
$strstores the stringtesters.
- The variable
-
strlen($str)- PHP counts the length of the string.
testershas7characters.
-
strlen($str) - 17 - 1becomes6.- Index
6is the last character position.
-
$str[6]
Real World Use Cases
Getting the last character of a string appears in many practical situations:
Checking URL or path endings
$path = "/images/";
if ($path !== "" && $path[-1] === "/") {
echo "Path ends with a slash";
}
Validating simple input formats
$sentence = "Hello!";
if ($sentence !== "" && $sentence[-1] === "!") {
echo "This looks excited.";
}
Inspecting file extensions or separators
$filename = "report.";
if ($filename !== "" && $filename[-1] === ".") {
echo "Filename ends with a dot";
}
Cleaning data before storage
Real Codebase Usage
In real PHP projects, developers usually do more than just grab the last character. They often combine it with validation and guard clauses.
Guard clause for empty input
function getLastCharacter(string $value): ?string
{
if ($value === '') {
return null;
}
return substr($value, -1);
}
This pattern is common because it prevents invalid access and makes the function safer.
Validation before processing
function ensureTrailingSlash(string $path): string
{
if ($path === '') {
return '/';
}
if (substr($path, -1) !== '/') {
return $path . '/';
}
;
}
Common Mistakes
1. Forgetting that indexes start at 0
Broken code:
$str = "testers";
echo $str[strlen($str)];
Why it is wrong:
strlen("testers")is7- the last valid index is
6 - index
7is out of range
Correct version:
$str = "testers";
echo $str[strlen($str) - 1];
2. Not handling empty strings
Broken code:
$str = "";
echo $str[strlen($str) - 1];
Why it is wrong:
- is
Comparisons
| Approach | Example | Pros | Cons |
|---|---|---|---|
String indexing with strlen() | $str[strlen($str) - 1] | Clear how index is calculated | Slightly longer, must handle empty strings carefully |
| Negative offset indexing | $str[-1] | Very short and readable | Depends on PHP version support |
substr() | substr($str, -1) | Common, readable, works well for this task | Still not multibyte-safe for UTF-8 |
mb_substr() | mb_substr($str, -1) | Best for multibyte strings |
Cheat Sheet
Quick ways to get the last character in PHP
$str = "testers";
// 1. Using strlen + index
$last = $str[strlen($str) - 1];
// 2. Using negative offset
$last = $str[-1];
// 3. Using substr
$last = substr($str, -1);
// 4. Using mb_substr for UTF-8
$last = mb_substr($str, -1);
Safe pattern
if ($str !== "") {
$last = substr($str, -1);
} else {
$last = null;
}
Rules to remember
- String indexes start at
0 - Last index is
strlen($str) - 1
FAQ
What is the easiest way to get the last character of a string in PHP?
A common and readable way is:
substr($str, -1)
Can I use $str[-1] in PHP?
Yes, in modern PHP versions, negative string offsets can access characters from the end. If version compatibility matters, substr($str, -1) is often safer.
What happens if the string is empty?
There is no last character in an empty string. You should check for "" before trying to access the last character.
Is substr() better than strlen() with indexing?
For this specific task, many developers find substr($str, -1) simpler and easier to read. Both work for normal single-byte strings.
How do I get the last character of a UTF-8 string in PHP?
Use:
mb_substr($str, -1)
This is safer for multibyte characters such as é, 你, or emoji.
Mini Project
Description
Build a small PHP helper for username validation. The helper should inspect the last character of a username and decide whether it ends with a number, a letter, or an invalid symbol. This is useful because many real applications validate or normalize user input before storing it.
Goal
Create a PHP function that safely reads the last character of a string and classifies it.
Requirements
- Create a function that accepts a string and returns the last character or
nullif the string is empty. - Create a second function that classifies the last character as
letter,number, orother. - Test the functions with at least three sample usernames.
- Handle empty strings safely without errors.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.