str_starts_with() was introduced in PHP 8.0 and remains fully available and unchanged in PHP 8.4 and PHP 8.5. It performs a case-sensitive check to see if a string begins with a given substring.
Basic Syntax
→str_starts_with(string $haystack, string $needle): bool
→Returns true if $haystack starts with $needle, otherwise false.
Example 1: Basic Check (with Output)
<?php
$string = The lazy fox jumped over the fence ;if (str_starts_with($string, The )) {
echo "The string starts with The ";
}var_dump(str_starts_with($string, The )); // bool(true)
var_dump(str_starts_with($string, lazy )); // bool(false)
?>
Output:
The string starts with The
bool(true)
bool(false)
Example 2: Case Sensitivity (Important).
<?php
$string = The lazy fox jumped over the fence ;if (str_starts_with($string, nothe )) {
echo The string starts with "the" ;
} else {
echo "the" was not found because the case does not match ;
}
?>
Output:
"the" was not found because the case does not match
The check is strictly case-sensitive: The matches, but nothe does not.
Example 3: Empty String Behaviour
<?php
if (str_starts_with( abc , )) {
echo "All strings start with the empty string";
}
?>
Output:
All strings start with the empty string
Every string is considered to start with an empty string.