Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Refactoring strpos()

<?php

$a = 'cde';

if ( strpos($a, 'abc') === 0)       { /**/ }
// Replace with 
if ( str_starts_with($a, 'abc'))    { /**/ }

if ( strpos($a, 'abc') !== 0)       { /**/ }
// Replace with 
if ( !str_starts_with($a, 'abc'))   { /**/ }

?>

Converting an expression like strpos() === 0 to use str_starts_with() is simple and direct. However, caution is needed when the comparison involves a difference rather than equality. In such cases, replacing the functions isn’t a straightforward one-to-one substitution, as the logic and intent behind the original expression may change, leading to unexpected behavior if not handled carefully.

See Also

PHP Features

Last updated: 10 September 2026