PHP 8 reference · String Functions

PHP str_ends_with() Function

Check whether a string ends with a given substring, such as a file extension. Case-sensitive; added in PHP 8.0.

PHP 8 Since 8.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

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

Parameters

ParameterDescription
haystack The string to check.
needle The suffix to look for.

Return value

true or false.

Examples

Check an extensionTry it yourself
<?php
var_dump(str_ends_with("photo.JPG", ".jpg"));
var_dump(str_ends_with(strtolower("photo.JPG"), ".jpg"));

Output

bool(false)
bool(true)
Add a missing slashTry it yourself
<?php
$dir = "uploads";
if (!str_ends_with($dir, "/")) {
    $dir .= "/";
}
echo $dir, "\n";

Output

uploads/

Version history

VersionChange
PHP 8.0Added

In other languages

Was this page helpful?