[英]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. 我有一个像914027的数字,现在我想找到6位数字中的缺失数字,例如:该数字中缺少3、5、6、8。 I have 300 numbers so it is not easy to find, that's why I want to do it with code
我有300个数字,所以不容易找到,这就是为什么我要用代码来实现
$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 演示: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: 现在,您可以使用array_diff查找它们之间的区别:
$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. 如果您有很多数字,请将它们全部放在一个数组中,然后遍历它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.