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'
"; } // Check if string starts with 'hay' (should be false) if (str_starts_with('hello haystack', 'hay')) { echo "String starts with 'hay'
"; } else { echo "String does not start with 'hay'
"; } ?>
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'
"; } // Check if string ends with 'hello' (should be false) if (str_ends_with('hello haystack', 'hello')) { echo "String ends with 'hello'
"; } else { echo "String does not end with 'hello'
"; } ?>
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'
"; echo "Starts with 'Hello': " . ($starts_with_hello ? "Yes" : "No") . "
"; echo "Ends with 'World': " . ($ends_with_world ? "Yes" : "No") . "
"; ?>
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

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements