PHP str_starts_with() Function

Last updated on August 9, 2023

The str_starts_with() function is a built-in function that checks if the string starts with the provided string, in other words we can say it checks if a sentence or phrase starts with a specific word or an alphabet letter. It is introduced in PHP 8.0.

Syntax:

str_starts_with(string $string, string $substring);

Parameters:

  • String: This is the main string and the function takes to checks if it starts with a substring.
  • Substring: This is a substring that uses to check if the main string starts with this.

Detail:

  • PHP Version: 8 or Higher
  • Return Value: Boolean (true or false)

Example:

In this article we will be learning with a few examples. To begin with, we created a string that starts with “the” and ends with  “Lerdorf.”.

$response = str_starts_with("The founder of PHP is Rasmus Lerdorf.", "The");
var_dump($response);
// Output: bool(true)

In this example, two string based arguments have passed into str_starts_with() function to check if the second string exists in the first. In the output, the function returned true because the second string “The” exists in the first string.

The str_starts_with() function also checks sensitivity of alphabetic letters. To understand it, let’s convert the capital letter of “The” into a small letter.

$response = str_starts_with("The founder of PHP is Rasmus Lerdorf", "the");
var_dump($response);
// Output: bool(false)

In this case, the str_starts_with() returned false. It is because the first string doesn’t start with a small alphabetic letter. That’s in the output we got false with Boolean data type.

Conclusion

In this we explained, how does str_starts_with() function work? The str_starts_with() function checks if the string starts with substring. It accepts two parameters in which first is string and second is substring.


Written by
I am a skilled full-stack developer with extensive experience in creating and deploying large and small-scale applications. My expertise spans front-end and back-end technologies, along with database management and server-side programming.

Share on:

Related Posts

Tags: PHP, PHP-Functions,