Home > Mobile >  checking if values in both foreach is equal and displaying accordingly giving error in php
checking if values in both foreach is equal and displaying accordingly giving error in php

Time:06-02

i have two arrays which in which i am using foreach for them to display the result, here what i want is to check if id in the 1st array is present in the second, if not present then display them, i did the following code:

    foreach($name as $n){

            foreach($response as $r){

            if ($n->id != $r->cid) {
      
      
      echo $n->id;
      
      }
      }
      }

here the issue is if only one values is equal then its coming fine, but if 2 values are equal then all the results are displayed 2 times, like that if 3 then the results are displayed times and so on. can anyone please tell me how to fix this, thanks in advance

CodePudding user response:

You can try it :

$tmpIds = [];
foreach($name as $n){
    foreach($response as $r){
        if ($n->id != $r->cid) {
            if(!in_array($n->id, $tmpIds)){
                $tmpIds[] = $n->id;
                echo $n->id;
            }
        }
    }
}

Example

  • Related