str_starts_with and str_ends_with function in PHP 8

PHP 8 introduced two convenient string functions: str_starts_with() and str_ends_with(). These functions check if a given string starts or ends with another string, returning true if the condition is met, otherwise false.

str_starts_with() Function

This function checks if a string starts with a specified substring (needle). It performs a case-sensitive comparison.

Syntax

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

Example

<?php
    // Check if string starts with 'hello'
    if (str_starts_with('hello haystack', 'hello')) {
        echo "String starts with 'hello'<br>";
    }
    
    // Check if string starts with 'hay' (should be false)
    if (str_starts_with('hello haystack', 'hay')) {
        echo "String starts with 'hay'<br>";
    } else {
        echo "String does not start with 'hay'<br>";
    }
?>
String starts with 'hello'
String does not start with 'hay'

str_ends_with() Function

This function checks if a string ends with a specified substring (needle). Like str_starts_with(), it also performs a case-sensitive comparison.

Syntax

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

Example

<?php
    // Check if string ends with 'stack'
    if (str_ends_with('hello haystack', 'stack')) {
        echo "String ends with 'stack'<br>";
    }
    
    // Check if string ends with 'hello' (should be false)
    if (str_ends_with('hello haystack', 'hello')) {
        echo "String ends with 'hello'<br>";
    } else {
        echo "String does not end with 'hello'<br>";
    }
?>
String ends with 'stack'
String does not end with 'hello'

Combined Example

<?php
    $text = "Hello World";
    
    // Test both functions
    $starts_with_hello = str_starts_with($text, "Hello");
    $ends_with_world = str_ends_with($text, "World");
    
    echo "Text: '$text'<br>";
    echo "Starts with 'Hello': " . ($starts_with_hello ? "Yes" : "No") . "<br>";
    echo "Ends with 'World': " . ($ends_with_world ? "Yes" : "No") . "<br>";
?>
Text: 'Hello World'
Starts with 'Hello': Yes
Ends with 'World': Yes

Conclusion

The str_starts_with() and str_ends_with() functions provide a clean, readable way to check string prefixes and suffixes in PHP 8. They are case-sensitive and return boolean values, making them perfect for conditional logic and string validation.

Updated on: 2026-03-15T09:43:51+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements