PHP str_starts_with() Function
PHP str_starts_with() Syntax
str_starts_with(string $haystack, string $needle): bool
PHP str_starts_with() Basic examples
var_dump(str_starts_with("Hello world", "Hello"));
bool(true)
Returns true if the string starts with the given substring.
var_dump(str_starts_with("Hello world", "world"));
bool(false)
Returns false if the substring is not at the start.
PHP str_starts_with() Real-world usage
$path = "/api/users";
if (str_starts_with($path, "/api")) {
echo "API route";
}
API route
Detects URL prefixes.
PHP str_starts_with() Edge cases
var_dump(str_starts_with("test", ""));
bool(true)
An empty string is always a valid prefix.
PHP str_starts_with() Common mistakes
Reimplementing prefix checks manually
Using substr or strpos is unnecessary.
substr("test", 0, 2) === "te";
str_starts_with("test", "te");
Use str_starts_with() for clarity and safety.
PHP str_starts_with() Frequently Asked Questions
What does str_starts_with() do in PHP?
str_starts_with() checks if a string starts with a given substring and returns true or false.
Is str_starts_with() case-sensitive?
Yes, str_starts_with() is case-sensitive.
What does str_starts_with() return?
It returns true if the string starts with the given substring, otherwise false.
Can str_starts_with() return 0?
No, it always returns a boolean value.
Is str_starts_with() available in all PHP versions?
No, it was introduced in PHP 8.0.
How to replicate str_starts_with() in older PHP?
Use strncmp($string, $search, strlen($search)) === 0.
Does str_starts_with() support empty strings?
Yes, every string starts with an empty string, so it returns true.
Does str_starts_with() modify the string?
No, it only checks the condition and does not modify the string.
Is str_starts_with() multibyte-safe?
It operates on bytes and may not fully support multibyte encodings.
What is the difference between str_starts_with() and strpos()?
str_starts_with() returns a boolean, while strpos() returns position or false.
What is a real-world use case of str_starts_with()?
It is commonly used to validate prefixes such as URLs, file paths, or tokens.
Can str_starts_with() be used for validation?
Yes, it is often used to validate input patterns or prefixes.