Open In App

PHP str_ends_with() Function

Last Updated : 06 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The str_ends_with() function is a predefined function in PHP 8 that is used to perform case-sensitive searching on a given string. The str_ends_with() generally checks for the string if it is ending with the substring or not. If the string ends with the substring then str_ends_with() will return TRUE otherwise it will return FALSE. It is very similar to str_starts_with() the only key difference between str-starts_with() and str_ends_with() is that str-starts_with() searches for the substring at beginning of the string whereas str_ends_with() searches for the substring at end of the string.

Syntax:

str_starts_with(string $string, string $substring) 

Parameters:

  • $string: $string refers to the string whose ending string needs to be searched.
  • $substring: $substring is the string that needs to be searched in the $string.

Key Features:

  • It is case-sensitive in nature.
  • It always returns a Boolean value.
  • It can be used to check the ending of both the String as well as a Character.
  • It always returns TRUE if the substring is empty or NULL, Since every string ends with NULL.
  • It is not supported on version of PHP smaller than 8.

Example 1: In this example, three variables has been created. $string to store the string value, $endsWith to store the value that will be searched at the end of the $string, and $result to store the result value. In the program if the string $endsWith will be found at the end of the $string then the function str_ends_with() will return TRUE otherwise it will return FALSE to the ternary operator and value for the variable $result will be assigned accordingly.  

PHP




<?php
 
    $string = 'GFG is awesome';
    $endsWith = 'some';
 
    $result = str_ends_with($string, $endsWith) ? 'is' : 'is not';
 
    echo "The string \"$string\" $result ending with $endsWith";
 
?>


Output :

The string "GFG is awesome" is ending with some

Example 2: In this example, we have created two variables $string to store a string and $endsWith to store the ending value that needs to be checked at the end of the $string. Here, the value for $endsWith will be empty and we will be checking if the string ends with an empty string or not. In such case output for the if-condition will always be TRUE since all the strings end with ‘\0’ and the output will be displayed accordingly.  

PHP




<?php
 
    $string = 'Checking for Blanks in the string';
    $endsWith = '';
 
    if(str_ends_with($string, $endsWith)) {
      echo 'Given String ends with an empty string';     
    }
    else {
      echo 'Given String does not ends with an empty string';
    }
 
?>


 
Output:

 Given String ends with an empty string

Reference: https://www.php.net/manual/en/function.str-ends-with.php

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads