PHP str_ends_with() Function: Complete Guide with Examples

When working with strings in PHP, developers often need to check whether a value ends with a particular word, character, file extension, or piece of text. For example, you might want to check whether a filename ends with .pdf or whether a URL ends with a slash. PHP provides the str_ends_with() function to make this type of check simple and readable.

PHP str_ends_with() function example showing how to check whether a string ends with a specific substring

Example of the PHP str_ends_with() function for checking the ending of a string.

The str_ends_with() function was introduced in PHP 8.0 and provides a straightforward way to determine whether a string ends with another string. It returns a boolean result, making it useful for conditions where you need to check whether specific text appears at the end of a string.

In this tutorial, you will learn how str_ends_with() works, how to use it in real coding situations, and what to keep in mind when comparing strings.

What Is the PHP str_ends_with() Function?

The PHP str_ends_with() function checks whether a string ends with a specified substring. It returns true if the ending matches exactly and false if it does not.

The function was introduced in PHP 8.0. Before PHP 8.0, developers generally used other string functions or a custom function to perform the same check.

For example, suppose you have a filename named report.pdf and want to check whether it ends with .pdf. You can write:

<?php
$filename = "report.pdf";

var_dump(str_ends_with($filename, ".pdf"));
?>

Output: bool(true)

The result is true because report.pdf ends with .pdf.

PHP str_ends_with() Syntax

The syntax of the function is straightforward:

str_ends_with(string $haystack, string $needle): bool

The function accepts two string arguments and returns a Boolean value.

Parameters

Parameter Description
$haystack The main string whose ending you want to check.
$needle The substring that PHP checks for at the end of the main string.

Both parameters are required. The comparison is case-sensitive, which means uppercase and lowercase letters are treated as different characters.

Return Value

The function returns one of two Boolean values:

  • true — when the main string ends with the specified substring.
  • false — when the ending does not match.

It does not return the matching substring or its position. It only tells you whether the ending matches.

PHP Version

str_ends_with() is available in PHP 8.0 and later. If your project runs on PHP 7.x or an earlier version, the native function is not available unless your application or framework provides a compatible implementation.

Basic Example of str_ends_with() in PHP

Let's start with a simple example that checks whether a sentence ends with a particular word.

<?php
$message = "Welcome to PHP";

if (str_ends_with($message, "PHP")) {
    echo "The sentence ends with PHP.";
} else {
    echo "The sentence does not end with PHP.";
}
?>

Output: The sentence ends with PHP.

Here, $message contains the text Welcome to PHP. Since the final three characters are PHP, the condition evaluates to true.

If you change the check to "Java", the function returns false because the sentence does not end with that text.

Practical Examples of PHP str_ends_with()

1. Check Whether a Filename Ends with .pdf

This is a common use case when an application handles uploaded documents or displays files with different extensions.

<?php
$filename = "invoice.pdf";

if (str_ends_with($filename, ".pdf")) {
    echo "This filename ends with .pdf.";
} else {
    echo "This filename does not end with .pdf.";
}
?>

Output: This filename ends with .pdf.

This example checks the filename's ending only. It does not prove that the file exists, contains a valid PDF document, or is safe to open. For uploaded files, use proper upload validation and content checks as well.

2. Check a File Extension Without Case Sensitivity

File extensions may be written with different letter cases. For example, PHOTO.JPG and photo.jpg have different letter casing, but you may want to treat both as JPEG filenames.

Since str_ends_with() is case-sensitive, normalize the filename before checking it.

<?php
$filename = "PHOTO.JPG";

if (str_ends_with(strtolower($filename), ".jpg")) {
    echo "The filename has a JPG extension.";
} else {
    echo "The filename does not have a JPG extension.";
}
?>

Output: The filename has a JPG extension.

The strtolower() function converts ASCII uppercase letters to lowercase. For ordinary ASCII file extensions, this makes the comparison easier. Remember that this is a string check, not complete file validation.

3. Check Whether a URL Ends with a Slash

Sometimes a project needs to check whether a URL string ends with / before formatting or processing it.

<?php
$url = "https://example.com/products/";

if (str_ends_with($url, "/")) {
    echo "The URL ends with a slash.";
} else {
    echo "The URL does not end with a slash.";
}
?>

Output: The URL ends with a slash.

This is useful for simple formatting checks. However, a matching ending does not establish that a URL is valid or trustworthy. Use appropriate URL parsing and validation when the URL affects security-sensitive operations.

4. Check Whether a String Ends with a Specific Word

You can also check the final word or phrase in a message.

<?php
$status = "Your order has been shipped";

if (str_ends_with($status, "shipped")) {
    echo "The order message ends with shipped.";
} else {
    echo "The expected ending was not found.";
}
?>

Output: The order message ends with shipped.

Keep in mind that this checks the exact ending. If the message changes to Your order has been shipped., including a full stop, checking for shipped will return false because the string actually ends with a period.

5. Check a String Ending Stored in a Variable

The substring you want to match does not have to be written directly inside the function. You can store it in a variable and reuse it.

<?php
$filename = "backup.sql";
$extension = ".sql";

if (str_ends_with($filename, $extension)) {
    echo "The file has the expected extension.";
} else {
    echo "The file has a different extension.";
}
?>

Output: The file has the expected extension.

This approach is useful when the expected suffix comes from a configuration value or when the same check is needed in several places.

6. Check Multiple Possible Endings

If a feature supports more than one file extension, you can use multiple checks with the logical OR operator (||).

<?php
$filename = "notes.txt";

if (
    str_ends_with($filename, ".txt") ||
    str_ends_with($filename, ".md")
) {
    echo "The filename ends with a supported text extension.";
} else {
    echo "The filename does not have a supported text extension.";
}
?>

Output: The filename ends with a supported text extension.

Each condition checks one possible ending. The overall condition is true when at least one of the checks returns true.

Case Sensitivity in str_ends_with()

One important detail is that str_ends_with() compares text exactly, including letter case. The strings "PHP" and "php" are not equal for this check.

<?php
$text = "Learn PHP";

var_dump(str_ends_with($text, "PHP"));
var_dump(str_ends_with($text, "php"));
?>

Output:
bool(true)
bool(false)

The first check succeeds because the string ends with uppercase PHP. The second fails because the supplied substring uses lowercase letters.

If the comparison should ignore ASCII letter case, normalize the relevant strings first:

<?php
$text = "Learn PHP";
$suffix = "php";

var_dump(
    str_ends_with(strtolower($text), strtolower($suffix))
);
?>

Output: bool(true)

For international text, be careful with case conversion. strtolower() is not a complete Unicode-aware case-folding solution. If your application handles multilingual text, consider the appropriate multibyte string functions and encoding requirements.

What Happens When the Needle Is an Empty String?

If the second argument is an empty string (""), str_ends_with() returns true.

<?php
var_dump(str_ends_with("Hello", ""));
var_dump(str_ends_with("", ""));
var_dump(str_ends_with("", "Hello"));
?>

Output:
bool(true)
bool(true)
bool(false)

This behavior can matter when the suffix comes from user input or configuration. If an empty suffix should not be accepted in your application, check for it separately before calling the function.

Common Mistakes to Avoid

1. Expecting a Case-Insensitive Comparison

This check does not match:

<?php
var_dump(str_ends_with("report.PDF", ".pdf"));
?>

Output: bool(false)

The extension uses uppercase letters, while the suffix uses lowercase letters. Normalize the strings if your requirements call for a case-insensitive comparison.

2. Using the Function in PHP 7

The native str_ends_with() function was introduced in PHP 8.0. Running code that calls it on PHP 7 without a compatible implementation can result in an undefined-function error.

Check your project's PHP version before using it, especially when working on an older hosting environment.

3. Forgetting Punctuation at the End

Consider this example:

<?php
$message = "Payment completed.";

var_dump(str_ends_with($message, "completed"));
?>

Output: bool(false)

The sentence ends with a period, not with the letter d. The function does not ignore punctuation or automatically trim whitespace.

4. Treating a Suffix Check as Full Validation

A filename ending in .jpg is not necessarily a valid image, and a URL ending in a particular string is not necessarily safe. Use str_ends_with() for the comparison it is designed to perform, and apply separate validation where necessary.

str_ends_with() vs str_starts_with() vs str_contains()

PHP provides several string functions that look for a substring, but each checks a different part of the string.

Function What it checks Example
str_starts_with() Whether the string begins with the specified substring. str_starts_with("report.pdf", "report")
str_ends_with() Whether the string ends with the specified substring. str_ends_with("report.pdf", ".pdf")
str_contains() Whether the substring appears anywhere in the string. str_contains("report.pdf", "port")

All three functions were introduced in PHP 8.0 and perform case-sensitive checks. Choose the function that matches the condition you actually need rather than using a broader search unnecessarily.

Best Practices for Using str_ends_with()

  • Use it for clear ending checks. The function makes your intention easier to understand than a longer combination of string operations.
  • Remember case sensitivity. Normalize strings only when your application requirements call for case-insensitive matching.
  • Handle empty suffixes deliberately. An empty second argument returns true.
  • Check PHP compatibility. The native function requires PHP 8.0 or later.
  • Keep validation separate. A suffix match alone does not establish that a file, URL, or other input is valid or safe.
  • Avoid unnecessary transformations. If you need a normalized value several times, calculate it once and reuse it where appropriate.

The function is binary-safe, but that does not make it a Unicode-aware text comparison function. When working with multibyte text, choose string operations that suit the encoding and comparison rules of your application.

Related PHP String Functions

If you are learning PHP string handling, these RaysCoding tutorials cover other useful string operations:

Frequently Asked Questions About str_ends_with()


What does str_ends_with() do in PHP?

The function checks whether a string ends with a specified substring. It returns true if the ending matches and false otherwise.


Which PHP version introduced str_ends_with()?

The native str_ends_with() function was introduced in PHP 8.0.


Is str_ends_with() case-sensitive?

Yes. Uppercase and lowercase letters are compared exactly. For example, checking whether "report.PDF" ends with ".pdf" returns false.


What does str_ends_with() return?

It returns a Boolean value: true when the string ends with the specified substring and false otherwise.


What happens when the second argument is an empty string?

The function returns true when the second argument is an empty string, including when the main string is also empty.


Can str_ends_with() check file extensions?

Yes. For example, str_ends_with($filename, ".pdf") checks whether a filename ends with .pdf. This check alone does not validate the file's actual contents or safety.


Is str_ends_with() the same as str_contains()?

No. str_ends_with() checks the end of a string, while str_contains() checks whether a substring appears anywhere in it.


Can I use str_ends_with() in PHP 7?

The native function is not available in PHP 7. You need PHP 8.0 or later, or a compatible implementation supplied by your application or framework.

Conclusion

The PHP str_ends_with() function provides a direct way to check whether a string ends with a particular substring. It is useful for simple checks involving filenames, file extensions, URLs, messages, and other text values.

Keep its case-sensitive behavior and PHP 8.0 requirement in mind. Also remember that matching an ending is only one check, not a replacement for proper input validation. With these details understood, str_ends_with() can make your PHP code easier to read and maintain.

Post a Comment

Previous Post Next Post