Search code examples
phpwhile-loopoffsetstrpos

strpos of 0 breaking while loop


So once again I'm practicing PHP. Specifically strpos() in a while loop.

The trouble with the below code is that strpos() results in 0 at the first loop, which yields a false result in the while condition, thus terminating the loop.

$string = 'orem ipsum dolor sit amet, consectetur adipisicing elit.';
$find = 'o';
$offset = 0;
$length  = strlen($find);

while ($string_pos = strpos($string, $find, $offset)) {
    echo 'String '.$find.' found at position '.$string_pos.'.<br>';
    $offset = $length + $string_pos;
}

I'm quite new to all of this, could someone help me with an explanation and a solution? I'm looking for it to loop all occurrences.


Solution

  • If you don't want to use strpos():

    <?php
    
    $string = 'orem ipsum dolor sit amet, consectetur adipisicing elit.';
    $find = 'o';
    
    for($i = 0; $i <= strlen($string)-1; $i++){
        // we are checking with each index of the string here
        if($string[$i] == $find){
            echo 'String '.$find.' found at position '.$i.'.<br>';
        }
    }
    
    ?>