How to compare these 2 arrays to check for a match-Collection of common programming errors

I need to compare the data coming from a database field with values from an array, to see if I have a match and select that match.

This is what I have:

$lookingfor = explode(",", $users_looking_for);
$i = 0;
foreach($i_am_looking_for_array as $key => $value){ 
 if($value==$lookingfor[$i]){
   echo ''.$value.$i.'';}
 else {
   echo ''.$value.$i.'';}
$i ++;
}

So, the $lookingfor gets the data stored on a DB field in the format (blue,black,white) and the $im_looking_for_array has the same options. My objective here is to have a drop-down fields with all the options available from the $im_looking_for_array and if one matches, mark it SELECTED in the multi-select drop-down field.

What is happening with my code above is that it only picks up the first match! Any ideas? Thanks a lot.

  1. I think that the problem with your code is that you only have one loop. So you only compare things at the same index. If the arrays would have different length, this could even lead to errors (undefined index if count($i_am_looking_for_array) > count($lookingfor)).

    How about using in_array?

    $lookingfor = explode(",", $users_looking_for);
    
    foreach($i_am_looking_for_array as $key => $value){ 
     if(in_array($value, $lookingfor))
       echo ''.$value.$key.'';
     else
       echo ''.$value.$key.'';
    }
    

Originally posted 2013-11-09 22:52:01.