Search code examples
phpstrpos

Iterating through string to find missing numbers not working


The following code should print ,2,6,7,8 - At least I want it to. what the heck am I missing? The intent is to find missing numerals in a long number.

$x = 1;
$missing = "";
$newfname = "193555415493359"; 
while($x <= 9) {
    $pos = strpos($newfname,$x);
    if($pos === false) {        
        $missing .= ",$x";                  
    }
    $x++;
} 
echo $missing;

Solution

  • According to the function documentation, "If needle is not a string, it is converted to an integer and applied as the ordinal value of a character." In other words, if you pass it 9, it's looking for a tab character (ASCII 9.)

    Try this instead:

    $x = 1;
    $missing = "";
    $newfname = "193555415493359"; 
    while($x <= 9) {
        $pos = strpos($newfname, (string)$x);
        if($pos === false) {        
            $missing .= ",$x";                  
        }
        $x++;
    } 
    echo $missing;
    

    The only change is to cast $x as a string for the search.

    Though, this could be done more efficiently:

    $haystack = "193555415493359";
    $needles = "123456789";
    $missing = array_diff(str_split($needles), str_split($haystack));
    echo implode(",", $missing);