Question

How to Get the Last Character of a String in PHP

phpstring

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:

  • t is box 0
  • e is box 1
  • s is box 2
  • t is box 3
  • e is box 4
  • r is box 5
  • s is box 6

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":

  • -1 means the last character
  • -2 means the second-to-last character
Take Quiz

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
  • - 1 gives 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 = "testers";
$lastChar = substr($str, -1);

echo $lastChar; // s

This is a very common and readable solution. substr($str, -1) means "take 1 character starting from the end."

4. Multibyte-safe version with mb_substr()

$str = "café";
$lastChar = mb_substr($str, -1);

echo $lastChar; // é

Use this when working with UTF-8 text that may contain non-ASCII characters.

Safe example with empty-string check

$str = "testers";

if ($str !== "") {
    echo $str[strlen($str) - 1];
} else {
    echo "String is empty";
}

This avoids trying to read a character from an empty string.

Step by Step Execution

Consider this code:

$str = "testers";
$lastChar = $str[strlen($str) - 1];
echo $lastChar;

Here is what happens step by step:

  1. $str = "testers";

    • The variable $str stores the string testers.
  2. strlen($str)

    • PHP counts the length of the string.
    • testers has 7 characters.
  3. strlen($str) - 1

    • 7 - 1 becomes 6.
    • Index 6 is the last character position.
  4. $str[6]

    • PHP reads the character at index 6.
    • That character is s.
  5. $lastChar = ...

    • The variable $lastChar now contains s.
  6. echo $lastChar;

    • PHP prints s.

Visual trace

IndexCharacter
0t
1e
2s
3t
4e
5r
6s

So the last character is at index 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

$code = "ABC-";

if ($code !== "" && $code[-1] === "-") {
    $code = rtrim($code, "-");
}

In real applications, this kind of logic is often part of validation, sanitization, routing, or formatting.

Take Quiz

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 . '/';
    }

    return $path;
}

Choosing the right tool for text encoding

In codebases that handle user input, APIs, or international text, developers often prefer mb_substr() over direct indexing for safety with UTF-8 strings.

function getLastUtf8Character(string $value): ?string
{
    if ($value === '') {
        return null;
    }

    return mb_substr($value, -1);
}

Common project patterns

  • Guard clauses: return early if the string is empty
  • Validation: check format before saving data
  • Formatting helpers: normalize paths, URLs, codes, or labels
  • Reusable utility functions: avoid repeating the same string logic across files

Common Mistakes

1. Forgetting that indexes start at 0

Broken code:

$str = "testers";
echo $str[strlen($str)];

Why it is wrong:

  • strlen("testers") is 7
  • the last valid index is 6
  • index 7 is 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:

  • strlen($str) is 0
  • 0 - 1 becomes -1
  • this can cause warnings or unexpected behavior depending on approach and PHP version

Safer version:

$str = "";

if ($str !== "") {
    echo substr($str, -1);
}

3. Assuming byte-based functions always work for Unicode

Problem example:

$str = "é";
echo $str[0];

This may not behave correctly for multibyte characters in UTF-8.

Safer version:

$str = "é";
echo mb_substr($str, 0, 1);

4. Using complicated code for a simple task

Overcomplicated code:

$str = "testers";
$chars = str_split($str);
echo $chars[count($chars) - 1];

This works, but it is less efficient and less direct than substr($str, -1) or $str[-1].

5. Forgetting PHP version compatibility

$str = "testers";
echo $str[-1];

Negative string offsets are convenient, but older PHP versions may not support them. If compatibility matters, substr($str, -1) is usually the safer choice.

Comparisons

ApproachExampleProsCons
String indexing with strlen()$str[strlen($str) - 1]Clear how index is calculatedSlightly longer, must handle empty strings carefully
Negative offset indexing$str[-1]Very short and readableDepends on PHP version support
substr()substr($str, -1)Common, readable, works well for this taskStill not multibyte-safe for UTF-8
mb_substr()mb_substr($str, -1)Best for multibyte stringsRequires mbstring extension

Which one should you use?

  • Use substr($str, -1) for a simple, readable general solution.
  • Use $str[-1] if your PHP version supports it and you want concise syntax.
  • Use mb_substr($str, -1) when working with UTF-8 or international text.
  • Use $str[strlen($str) - 1] if you want to understand or demonstrate indexing clearly.
Take Quiz

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
  • Empty strings need special handling
  • substr($str, -1) is a common choice
  • mb_substr() is safer for multibyte text

Edge cases

  • Empty string: no last character exists
  • Unicode text: use mb_substr() when needed
  • Older PHP versions: check support for negative offsets

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.

Why does strlen($str) not give the last character directly?

strlen($str) gives the length, not an index. Because indexes start at 0, the last character is at strlen($str) - 1.

Can I get the last two characters instead?

Yes. With substr() you can do:

substr($str, -2)
Take Quiz

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 null if the string is empty.
  • Create a second function that classifies the last character as letter, number, or other.
  • Test the functions with at least three sample usernames.
  • Handle empty strings safely without errors.
Take Quiz

Keep learning

Related questions

View more