###### dtsc14683
2018-04-11 06:32 阅读 14

# 获取for循环中不存在的数字

I have 2 integers.

``````\$a = 5;
\$b = 3;
``````

This is my code as of now, I want to do it vice versa, which is to get the integer that does not exist. Instead of getting the existing numbers which are 1,2,3. I would like to execute a command on the numbers that does not exist (4 & 5).

``````for (\$x = 1; \$x <= \$a; \$x++) {
for (\$y = 1; \$y <= \$b; \$y++) {
if (\$x == \$y)
{
echo \$y." = Exist Do some commands here<br>";
}
}
}
``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 2条回答默认 最新

• 已采纳
doukan5332 2018-04-11 06:47

You can use the following solution:

``````<?php
\$a = 3;
\$b = 5;

\$arrNotExists = [];

for (\$i = \$a + 1; \$i <= \$b; \$i++) {
\$arrNotExists[] = \$i;
}

var_dump(\$arrNotExists);
``````

Another solution using two arrays with `array_diff`:

``````<?php
\$a = 3;
\$b = 5;

\$arrA = [];
\$arrB = [];

for (\$i = 1; \$i <= \$a; \$i++) {
\$arrA[] = \$i;
}

for (\$i = 1; \$i <= \$b; \$i++) {
\$arrB[] = \$i;
}

\$arrNotExists = array_diff(\$arrB, \$arrA);

var_dump(\$arrNotExists);
``````
点赞 评论 复制链接分享
• dongzou7134 2018-04-11 07:04

According to description as mentioned into above question as a solution to it please try executing following code snippet

``````\$a = 5;
\$b = 3;
\$temp=array();
\$result=array();
for (\$x = 1; \$x <= \$a; \$x++) {
for (\$y = 1; \$y <= \$b; \$y++) {
\$temp[]=\$y;

}
if(in_array(\$x,\$temp)==false)
{
\$result[]=\$x;
}
}
``````

Also please try executing another alternative solution

``````\$a1 = range(1, \$a);
\$a2 = range(1, \$b);
\$result = array_diff(\$a1, \$a2);
``````
点赞 评论 复制链接分享