Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP str_ends_with() function

Reference for PHP str_ends_with(): test whether a string ends with a given suffix, case sensitivity, the empty suffix rule and how to check file extensions.

str_ends_with() returns true when a string finishes with the given suffix and false otherwise. It was added in PHP 8.0 and replaces expressions like substr($s, -4) === ".php", which break on short strings and are noisy to read.

Like its sibling str_starts_with(), it is case-sensitive and byte-based, and an empty suffix always matches.

PHP
<?php
var_dump(str_ends_with("report.pdf", ".pdf"));   // bool(true)
var_dump(str_ends_with("report.PDF", ".pdf"));   // bool(false)

Try it

PHP Checking suffixes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP File extensions and trailing slashes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
str_ends_with(string $haystack, string $needle): bool
Name Description
$haystack The string to check.
$needle The suffix to look for. An empty string always matches.

Return value: true if $haystack ends with $needle, otherwise false.

Errors: a TypeError is thrown for arguments that cannot be converted to a string (such as arrays), and for non-string scalars under declare(strict_types=1).

Usage notes

  • Case-sensitive. Normalize case first (strtolower() or mb_strtolower()) when comparing extensions.
  • Empty suffix is always found, even on an empty haystack.
  • A suffix longer than the string returns false instead of a warning, unlike the manual substr trick.
  • Extensions. For file names, pathinfo($name, PATHINFO_EXTENSION) is usually clearer when you need the extension itself; str_ends_with() suits a quick yes/no check, including multi-part extensions such as .tar.gz.
  • Never trust the extension for security. Uploaded files can lie about their type.
  • Added in PHP 8.0. Older code can use substr_compare($s, $suffix, -strlen($suffix)) === 0, taking care with strings shorter than the suffix.
  • Not a pattern match. Characters like * are literal here.