Home » Php » php – Compare all value of two array in one foreach

php – Compare all value of two array in one foreach

Posted by: admin February 25, 2020 Leave a comment

Questions:

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

How to&Answers:

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

Answer:

In your assoc arrays you have dublicate keys. So if you use:

print_r( $array1 );

You’ll see that your array only contains the last entry:

Array ( [user_id] => 3 )

I think that is not what you have expected. So you have to use different keys like that:

$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');

Or you even dont use assoc arrays because it is obsolete in your example but never mind:

$user_ids = array('1','2','3');
$invited_user_ids = array('1','3');

You can compare your assoc arrays like that:

$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');

foreach ($array1 as $user_id) {
  if( in_array( $user_id, $array2 ) ) {
    echo "Matched id: $user_id";
  }
}