Skip to content
Advertisement

Compare all value of two array in one foreach

I’ve 2 array in php

$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');

This is a result of select query wrote in codeigniter. so that is associative array. This is 2 query result one is for user list and second is for invited user list. I want check in user list which user is invited. So that I want to compare that array

foreach ($array1 as $key => $value) {
  if($array2[$key]->invite_user_id==$value->user_id) {
    echo "Matched"; 
  }
}

but it compare only 2 value of array1 with array2 3rd value is not compare. How it could compare all value of array1 and array2 in above foreach loop

Advertisement

Answer

I found that answer

$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');

$invitationset = [];
foreach ($array2 as $invite) {
  $invitationset[$invite->invite_user_id] = $invite->invite_user_id;
}

foreach ($array1 as $key => $value) {
  if(isset($invitationset[$value->user_id])){ 
    if($invitationset[$value->id]==$value->user_id){
      echo "Matched";
    }
  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement