I have a php comma separated string
$string = (x,y,z)
I have a column in mysql that has items (y,z)
I want to make an array of the items that are in the string but not in the table column…
$cid = "'" . str_replace(",", "','", $cid) . "'";
$query = mysql_query("SELECT save_key FROM saved WHERE save_key IN ($cid)");
while ($result = mysql_fetch_assoc($query)){
$array[] = $result['save_key'];
}
$cid_array = explode(',',$cid);
$dif = array_diff($cid_array, $array);
print_r($dif);
Output:
Array from query ( [0] => O45527 [1] => P97387 [2] => Y49437 )
Array from array_dif ( [0] => ‘P97387’ [1] => ‘O45527’ [2] => ‘Y49437’ )
all items are the same right..
print_r($dif); should return array()
Use
array_diff– it Computes the difference of arraysJust convert your strings in to array using
explodeand usearray_diffExample :
Note : Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.
Array from query ( [0] => O45527 [1] => P97387 [2] => Y49437 )
Array from array_dif ( [0] => ‘P97387’ [1] => ‘O45527’ [2] => ‘Y49437’ )
so O45527 and ‘O45527’ are different ans same for all that is why it’s returning whole array. Try to cast elemet values in same datatype.