PHP str_ends_with() Function

Quick summary: The PHP str_ends_with() function checks if a string ends with a given substring.

PHP str_ends_with() Syntax

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

PHP str_ends_with() Basic examples

var_dump(str_ends_with("Hello world", "world"));
PHP
Output:
bool(true)

Returns true when the string ends with the given substring.

var_dump(str_ends_with("Hello world", "Hello"));
PHP
Output:
bool(false)

Returns false when the substring is not at the end.

PHP str_ends_with() Real-world usage

$filename = "report.pdf";
if (str_ends_with($filename, ".pdf")) {
    echo "PDF file";
}
PHP
Output:
PDF file

Checks file extensions safely.

PHP str_ends_with() Edge cases

var_dump(str_ends_with("test", ""));
PHP
Output:
bool(true)

An empty string is always considered a valid suffix.

PHP str_ends_with() Common mistakes

Reimplementing suffix checks manually

Using substr is error-prone.

Incorrect
substr("file.txt", -4) === ".txt";
Correct
str_ends_with("file.txt", ".txt");

Use str_ends_with() for clarity and correctness.

PHP str_ends_with() Frequently Asked Questions

What does str_ends_with() do in PHP?

str_ends_with() checks if a string ends with a given substring.

Is str_ends_with() case-sensitive?

Yes, str_ends_with() is case-sensitive.

What does str_ends_with() return?

It returns true if the string ends with the given substring, otherwise false.

Is str_ends_with() available in all PHP versions?

No, it was introduced in PHP 8.0.

How to replicate str_ends_with() in older PHP?

Use substr($string, -strlen($search)) === $search.

Does str_ends_with() support empty strings?

Yes, every string ends with an empty string, so it returns true.

Does str_ends_with() modify the string?

No, it only checks and does not modify the string.

Is str_ends_with() multibyte-safe?

It operates on bytes and may not fully support multibyte encodings.

What is the difference between str_ends_with() and strrpos()?

str_ends_with() returns a boolean, while strrpos() returns the position of the last occurrence.

Can str_ends_with() be used for file extensions?

Yes, it is commonly used to check file extensions.

What is a real-world use case of str_ends_with()?

It is used to validate suffixes like file types, domains, or string endings.

Can str_ends_with() be used for validation?

Yes, it is useful for validating suffix patterns.

PHP str_ends_with() Related PHP Functions