简体   繁体   中英

How I can find the missing number in digit with php

I have a number like 914027, and now I want to find the missing numbers in the 6 digits eg: 3,5,6,8 are missing in that number. I have 300 numbers so it is not easy to find, that's why I want to do it with code

$str = '914027';
$one=$str[0];
$two=$str[1];
$three=$str[2];
$four=$str[3];
$five=$str[4];
$six=$str[5];

Something like

$str = '914027';
if ($missNumbers = array_diff(range('0','9'), str_split($str))) {
    echo sprintf("Missing: %s", implode(', ', $missNumbers));
}

Demo: http://3v4l.org/HelUL

You can use array functions for this.

Set an array with all the digits:

$digits = array("0","1","2","3","4","5","6","7","8","9");

Now split the number to an array:

$str = "914027";
$numDigits = str_split($str);

Now you can use array_diff to find the difference between them:

$missing = array_diff($digits, $numDigits);

The result will be an array with the missin digits:

["3","5","6","8"]

If you have a lot of numbers, put them all in an array, and loop through it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM