c18 online
c18 online

Reputation: 69

Get numbers that does not exist in for loop

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>";
        }
    }
}

Upvotes: 0

Views: 151

Answers (2)

Rubin Porwal
Rubin Porwal

Reputation: 3845

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);

Upvotes: 0

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You can use the following solution:

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

$arrNotExists = [];

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

var_dump($arrNotExists);

demo: https://ideone.com/bOSsH8

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);

demo: https://ideone.com/OtSwnN

Upvotes: 1

Related Questions