When working with strings in PHP, developers often need to check whether a string begins with a particular word, character, prefix, or piece of text. PHP provides the str_starts_with() function to make this type of check simple and readable.
PHP str_starts_with() Function in PHP 8+
The str_starts_with() function was introduced in PHP 8.0 and provides a straightforward way to determine whether a string begins with another string. It returns a boolean result, making it useful for conditions where you only need to know whether a specific prefix exists at the beginning of a string.
In this complete guide, you will learn what str_starts_with() does, how its syntax works, how to use its parameters, and how to handle its return value. We will also cover case sensitivity, empty strings, practical examples, real-world use cases, comparisons with other PHP string functions, common mistakes, and best practices.
What is str_starts_with() in PHP?
The PHP str_starts_with() function checks whether a given string starts with a specified substring. It returns true when the string begins with the specified substring and false when it does not.
This function is useful when you need to check the beginning of a string. Unlike str_contains(), which checks whether text exists anywhere inside a string, str_starts_with() specifically checks the beginning.
For example, if you have a sentence that starts with the word PHP, you can use str_starts_with() to check whether the string begins with that word.
<?php
$text = "PHP is a popular server-side programming language.";
if (str_starts_with($text, "PHP")) {
echo "The string starts with PHP.";
} else {
echo "The string does not start with PHP.";
}
?>
Output: The string starts with PHP.
Here, str_starts_with() checks whether "PHP" occurs at the beginning of the $text string. Because the string starts with PHP, the function returns true.
Why Use str_starts_with() in PHP?
The main reason to use str_starts_with() is readability. When your application needs to determine whether a string begins with a specific value, the function clearly communicates the purpose of the condition.
Before PHP 8.0, developers commonly used functions such as strpos() or substr() to perform similar checks. These approaches can still be useful in older PHP applications, but str_starts_with() provides a direct and expressive solution in PHP 8.0 and later.
- It clearly communicates that you are checking the beginning of a string.
- It returns a simple boolean value.
- It makes conditional statements easier to understand.
- It is useful for prefix and validation checks.
- It can be used for URLs, filenames, identifiers, and messages.
- It avoids unnecessary position or substring handling for a simple starts-with check.
PHP str_starts_with() Syntax
The syntax of the str_starts_with() function is:
str_starts_with(string $haystack, string $needle): bool
The function accepts two required string parameters. The first parameter is the complete string that you want to check, while the second parameter is the substring that should appear at the beginning.
| Parameter | Description |
|---|---|
$haystack |
The complete string whose beginning will be checked. |
$needle |
The substring that you want to check for at the beginning. |
The function returns a boolean value: true if the haystack starts with the specified needle and false otherwise.
Parameters Explanation
1. $haystack
The $haystack parameter contains the complete string that you want to examine. It can be a string variable, a literal string, a value returned from another function, or text retrieved from a database or request.
<?php
$message = "Welcome to RaysCoding PHP tutorials.";
$result = str_starts_with($message, "Welcome");
var_dump($result);
?>
Output: bool(true)
In this example, $message is the haystack because it contains the complete text being checked.
2. $needle
The $needle parameter contains the substring that you want to find at the beginning of the haystack.
<?php
$message = "Welcome to RaysCoding PHP tutorials.";
$prefix = "Welcome";
$result = str_starts_with($message, $prefix);
var_dump($result);
?>
Output: bool(true)
Here, "Welcome" is the needle because it is the text that we want to check at the beginning of the string.
Return Value of str_starts_with()
The str_starts_with() function returns a boolean value. It returns true when the haystack starts with the specified needle and false when it does not.
| Condition | Return Value |
|---|---|
| String starts with the specified substring | true |
| String does not start with the specified substring | false |
| Needle is an empty string | true |
Because the result is boolean, str_starts_with() works naturally with if, else, ternary expressions, and other conditional logic.
Basic Example of str_starts_with() in PHP
Let's start with a simple example where we check whether a sentence starts with the word Laravel.
<?php
$text = "Laravel is a PHP framework.";
if (str_starts_with($text, "Laravel")) {
echo "The text starts with Laravel.";
} else {
echo "The text does not start with Laravel.";
}
?>
Output: The text starts with Laravel.
Explanation: The string stored in $text begins with the word Laravel. Therefore, str_starts_with() returns true, and the first part of the if statement is executed.
Example: When the Substring Is Not at the Beginning
The function returns false when the specified substring exists somewhere in the string but does not occur at the beginning.
<?php
$text = "PHP is used with Laravel.";
if (str_starts_with($text, "Laravel")) {
echo "The string starts with Laravel.";
} else {
echo "Laravel is not at the beginning.";
}
?>
Output: Laravel is not at the beginning.
Explanation: The word Laravel exists inside the string, but the string actually starts with PHP. Therefore, str_starts_with() returns false.
This is an important difference between str_starts_with() and str_contains(). The latter checks for a substring anywhere in the string, while str_starts_with() checks only the beginning.
Case Sensitivity in str_starts_with()
One important point to remember is that str_starts_with() is case-sensitive. Uppercase and lowercase characters are treated as different characters during the comparison.
<?php
$text = "PHP is a popular language.";
var_dump(str_starts_with($text, "PHP"));
var_dump(str_starts_with($text, "php"));
?>
Output:
bool(true)
bool(false)
Explanation: The original string starts with PHP using uppercase letters. It does not start with lowercase php. Therefore, the first check succeeds and the second check fails.
If your application requires case-insensitive behavior, you can normalize both the haystack and needle before performing the comparison.
Case-Insensitive Search with strtolower()
PHP does not provide a separate case-insensitive version of str_starts_with(). A common approach is to convert both strings to the same case before performing the check.
<?php
$text = "Welcome to PHP Development.";
$prefix = "welcome";
if (str_starts_with(strtolower($text), strtolower($prefix))) {
echo "The string starts with Welcome.";
} else {
echo "The string does not start with Welcome.";
}
?>
Output: The string starts with Welcome.
Explanation: Both values are converted to lowercase before the comparison. The original Welcome therefore becomes welcome, allowing the comparison to succeed.
For Unicode-heavy or multilingual applications, simple case conversion may not cover every language-specific requirement. Use appropriate multibyte or locale-aware handling when your application needs it.
Checking an Empty String
An important behavior of str_starts_with() is that checking an empty string as the needle returns true.
<?php
$text = "PHP programming";
$prefix = "";
var_dump(str_starts_with($text, $prefix));
?>
Output: bool(true)
Explanation: An empty string is considered to occur at the beginning of every string. If an empty prefix is not meaningful for your application, validate the value before performing the check.
Example: Checking a URL Prefix
A practical use of str_starts_with() is checking whether a URL begins with a specific protocol or prefix.
<?php
$url = "https://www.rayscoding.com/";
if (str_starts_with($url, "https://")) {
echo "The URL uses HTTPS.";
} else {
echo "The URL does not use HTTPS.";
}
?>
Output: The URL uses HTTPS.
Explanation: The URL begins with https://, so the function returns true.
This type of check can be useful for simple application logic. However, security-sensitive URL validation should use appropriate URL parsing and validation rather than relying only on a prefix check.
Example: Checking a Filename Prefix
You can also use str_starts_with() to check whether a filename begins with a known prefix.
<?php
$filename = "invoice_2026_001.pdf";
if (str_starts_with($filename, "invoice_")) {
echo "This is an invoice file.";
} else {
echo "This is not an invoice file.";
}
?>
Output: This is an invoice file.
Explanation: The filename begins with invoice_, so the condition evaluates to true.
Advanced Example: Checking Multiple Prefixes
Sometimes an application needs to determine whether a string starts with one of several accepted prefixes. You can combine multiple str_starts_with() calls with the logical OR operator.
<?php
$username = "admin_amit";
if (
str_starts_with($username, "admin_") ||
str_starts_with($username, "manager_")
) {
echo "This username uses an administrative prefix.";
} else {
echo "No matching prefix was found.";
}
?>
Output: This username uses an administrative prefix.
Explanation: The username starts with admin_, so the first condition returns true. Because the conditions are connected with ||, the complete expression evaluates to true.
Advanced Example: Checking API Routes
Another practical use is identifying whether a request path starts with a particular API prefix.
<?php
$path = "/api/users/25";
if (str_starts_with($path, "/api/")) {
echo "This is an API route.";
} else {
echo "This is not an API route.";
}
?>
Output: This is an API route.
Explanation: The value stored in $path begins with /api/. Therefore, the function returns true.
In a real framework application, routing should normally be handled by the framework's routing system. This example demonstrates how the string function itself can be used for simple prefix-based logic.
Step-by-Step Code Explanation
Consider this example:
<?php
$title = "PHP Laravel Tutorial";
$prefix = "PHP";
if (str_starts_with($title, $prefix)) {
echo "The title starts with PHP.";
} else {
echo "The title does not start with PHP.";
}
?>
Step 1: The $title variable stores the complete string that we want to check.
Step 2: The $prefix variable stores the substring that should appear at the beginning.
Step 3: str_starts_with($title, $prefix) checks whether the title begins with the specified prefix.
Step 4: If the prefix exists at the beginning, the function returns true.
Step 5: The if statement displays the corresponding message.
Output: The title starts with PHP.
Real-World Use Cases of str_starts_with()
The str_starts_with() function can be useful in many PHP applications where the beginning of a string has meaning.
- URL handling: Check whether a URL starts with a particular protocol or path.
- API routes: Detect paths that begin with an API prefix.
- Filename processing: Identify files based on a known filename prefix.
- Form validation: Check whether submitted values begin with an expected prefix.
- Identifiers: Validate application-specific IDs such as
user_ororder_. - Message processing: Detect messages that begin with a known command or keyword.
- Log processing: Identify log entries based on a known prefix.
- Application filtering: Perform simple decisions based on the beginning of text values.
str_starts_with() vs str_contains()
Both str_starts_with() and str_contains() check whether a substring exists, but they answer different questions.
| Feature | str_starts_with() | str_contains() |
|---|---|---|
| Purpose | Checks whether a string starts with a substring | Checks whether a substring exists anywhere in a string |
| Return type | Boolean | Boolean |
| PHP version | PHP 8.0+ | PHP 8.0+ |
| Best for | Prefix checks | General substring presence checks |
| Position required | Beginning of the string | Anywhere in the string |
Use str_starts_with() when the substring must occur at the beginning. Use str_contains() when the substring can appear anywhere in the string.
You can also read our PHP str_contains() Function Tutorial to learn how to check whether a string contains a specific substring.
str_starts_with() vs strpos()
Before PHP 8.0, developers commonly used strpos() to determine whether a string started with a particular substring. The two functions have different return values and purposes.
| Feature | str_starts_with() | strpos() |
|---|---|---|
| Purpose | Checks whether a string starts with a substring | Finds the position of a substring |
| Return type | Boolean | Integer or false |
| PHP version | PHP 8.0+ | Available in older PHP versions |
| Prefix check | Direct and readable | Requires position comparison |
| Position information | Not returned | Returned when found |
If you only need to know whether a string starts with a specific substring and your application uses PHP 8.0 or later, str_starts_with() expresses that intention directly.
When you need the actual position of a substring, strpos() remains the appropriate function.
str_starts_with() vs str_ends_with()
PHP 8.0 also introduced str_ends_with(), which performs the opposite type of boundary check.
| Function | What it checks |
|---|---|
str_starts_with() |
Whether a string starts with a specific substring |
str_contains() |
Whether a string contains a specific substring anywhere |
str_ends_with() |
Whether a string ends with a specific substring |
Use str_starts_with() for beginning checks, str_contains() for general substring checks, and str_ends_with() when the substring must occur at the end.
Common Mistakes with str_starts_with()
1. Forgetting That the Function Is Case-Sensitive
A common mistake is expecting uppercase and lowercase values to match automatically. PHP and php are different during a normal str_starts_with() comparison.
2. Confusing It with str_contains()
str_starts_with() only checks the beginning of the string. A substring appearing later in the string does not produce true.
3. Forgetting the Empty String Behavior
An empty needle returns true. If the prefix comes from dynamic input, validate it first when an empty value should not be accepted.
4. Using It on Unsupported PHP Versions
str_starts_with() was introduced in PHP 8.0. Applications running older PHP versions need a compatible alternative such as strpos().
5. Treating a Prefix Check as Complete Validation
A simple prefix check only examines the beginning of a string. It should not be treated as complete validation for URLs, file paths, authentication data, or security-sensitive input.
6. Ignoring Leading Whitespace
If a string may contain unwanted spaces before the expected prefix, the check can return false even though the visible text appears to begin with the expected value.
<?php
$text = " PHP tutorial";
var_dump(str_starts_with($text, "PHP"));
?>
Output: bool(false)
If leading whitespace should not matter in your application, normalize the input before performing the comparison.
Best Practices for str_starts_with()
- Use
str_starts_with()when you need a clear prefix check. - Remember that the comparison is case-sensitive.
- Normalize values when your application requires case-insensitive matching.
- Validate dynamic prefixes before performing the check.
- Use
str_contains()when the substring can appear anywhere. - Use
str_ends_with()when the required substring belongs at the end. - Use proper URL, path, or input validation when simple prefix matching is not sufficient.
- Make sure your production application runs PHP 8.0 or a newer supported version.
- Keep prefix conditions readable and avoid unnecessary string manipulation.
Performance & Security Notes
str_starts_with() is designed for straightforward string-prefix checks and is generally appropriate for normal application logic.
For common operations such as checking a URL prefix, filename prefix, API path, identifier, or message command, the operation is normally inexpensive.
For very large strings or extremely high-frequency processing, avoid unnecessary repeated transformations and checks. If the same normalized value is needed multiple times, consider normalizing it once and reusing the result.
From a security perspective, str_starts_with() should not be considered a complete validation or authorization mechanism. A prefix check alone does not prove that a URL, path, request, or user-provided value is safe.
For security-sensitive input, use proper validation, parsing, escaping, authorization, and framework-level security mechanisms appropriate to the application.
Related PHP String Functions
PHP provides many functions for working with strings. If you are learning PHP string handling, the following tutorials on RaysCoding can help you continue your learning:
- PHP str_contains() Function Tutorial – Learn how to check whether a string contains a specific substring.
- PHP strlen() Function Tutorial – Learn how to get the length of a string.
- PHP count_chars() Function Tutorial – Learn how PHP analyzes characters used in a string.
- PHP chunk_split() Function Tutorial – Learn how to split strings into smaller chunks.
- PHP chr() Function Tutorial – Learn how to generate a character from an ASCII value.
- PHP chop() Function Tutorial – Learn how to remove whitespace or characters from the end of a string.
- PHP htmlspecialchars() Function Tutorial – Learn how to safely convert special HTML characters.
These tutorials are part of the broader PHP string-function learning path on RaysCoding.
Frequently Asked Questions About str_starts_with()
What does str_starts_with() do in PHP?
The PHP str_starts_with() function checks whether a string starts with a specified substring. It returns true when the string begins with the specified substring and false otherwise.
Is str_starts_with() case-sensitive in PHP?
Yes. The str_starts_with() function is case-sensitive. For example, searching for php will not match a string beginning with PHP. If you need case-insensitive behavior, you can normalize both strings before performing the comparison.
Which PHP version introduced str_starts_with()?
The str_starts_with() function was introduced in PHP 8.0. Applications running older PHP versions should use an appropriate alternative such as strpos() when necessary.
What does str_starts_with() return?
str_starts_with() returns a boolean value. It returns true if the haystack starts with the specified needle and false if it does not.
What happens when the needle is an empty string?
When the needle is an empty string, str_starts_with() returns true. If the prefix comes from dynamic input, validate it first if an empty value should not be accepted.
Is str_starts_with() better than strpos()?
The functions serve different purposes. str_starts_with() directly expresses a prefix check and returns a boolean value, while strpos() returns the position of a substring or false. Use the function that matches the requirement of your application.
Can str_starts_with() be used for URLs?
Yes. It can be used for simple checks such as determining whether a URL begins with https:// or a known path prefix. For security-sensitive URL validation, use appropriate URL parsing and validation instead of relying only on a prefix check.
Conclusion
The PHP str_starts_with() function provides a clean and readable way to check whether a string begins with a specific substring. Its boolean return value makes it especially useful for prefix checks, URL handling, filename processing, identifiers, API paths, message processing, and other everyday PHP tasks.
The most important things to remember are that str_starts_with() requires a haystack and a needle, returns true or false, is case-sensitive, treats an empty needle as a match, and is available from PHP 8.0 onward.
If you are learning PHP string functions, practice by checking URL prefixes, filenames, API paths, identifiers, and messages. After learning str_starts_with(), another useful function to learn is str_ends_with(), which performs a similar check at the end of a string.