Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

str_ends_with

Checks whether a string ends with a given substring.

Syntax

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

Parameters

ParameterTypeDescription
$haystackstringThe string to check.
$needlestringThe expected ending.

Return value

bool`true` if the string ends with the substring.

Examples

Checking a file extension:

<?php
 
var_dump(str_ends_with('report.pdf', '.pdf'));
var_dump(str_ends_with('report.pdf', '.doc'));

Output:

bool(true)
bool(false)

The comparison is case-sensitive:

<?php
 
var_dump(str_ends_with('PHOTO.JPG', '.jpg'));
var_dump(str_ends_with(strtolower('PHOTO.JPG'), '.jpg'));

Output:

bool(false)
bool(true)

Notes

The function appeared in PHP 8.0. An empty substring counts as the ending of any string.

See also

  • str_starts_with — Checks whether a string starts with a given substring.
  • str_contains — Checks whether a string contains a given substring.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.