Interview frequency: …
Short answer
They are intuitive built-in functions that check whether a string contains another string and return a boolean, replacing complex and error-prone strpos checks.
Explanation
Previously, checking a string prefix required strpos($str, $prefix) === 0. Developers could fall into the if (strpos(...)) trap because finding the text at position 0 returns 0, which is treated as false. PHP 8 added str_contains, str_starts_with, and str_ends_with, which take strings and clearly return true or false.
Code example
if (str_starts_with($path, "/api/")) {
// Route to API
}
if (str_contains($email, "@gmail.com")) {
// Validate
}Common mistakes
- Using if (strpos($haystack, $needle)) to check for a word, overlooking the position-0 trap.