Daniel Hunter
Daniel Hunter

Reputation: 2866

compare array to mysql column and find the unmatched items

I have a php comma seperated string $string = (x,y,z)

I have a column in mysql that has items (y,z)

how do i compare the two and echo which items in $string are not in the column?

Upvotes: 1

Views: 3463

Answers (4)

user319198
user319198

Reputation:

I think you want to compute differente in two comma separated strings.

Just convert your strings in to array using explode and use array_diff

array_diff - Computes the difference of arrays

Example :

<?php

$array1=explode(",",$string);
$array2=explode(",",$yourstring_of_db_column);
$array1 = array("x", "y", "z");
$array2 = array( "y","z");
$result = array_diff($array1, $array2);

print_r($result);
?>

Be aware Values are compared using ===, so 1 and "1" are considered different.

Upvotes: 0

Bogdan
Bogdan

Reputation: 865

you could solve this with one query, retrieving just the rows that do not match, eg.:

$string= "(str1, str2, str3)"; //formatted as the OP indicated
$input = explode(",",trim($string,"() "));
$filter = "(".$input[1].",".$input[2].")";

$sql = "select interestingColumn from greatTable where interestingColumn not like '".$filter."'";
$rez = mysql_query($sql);
while($row =  mysql_fetch_array($rez)){
     echo $row["interestingColumn"]."<br>\n";
}

this has the added benefit of retrieving fewer results from the database, which is desirable especially if you have a large dataset

edit : fixed a typo on the second line (thanks Michael)

Upvotes: 0

Adam Fowler
Adam Fowler

Reputation: 1751

I think that should do the trick. Good Luck.

$myString="v1,v2,v3";
$stringA=explode(",",$myString);

$result=mysql_query("SELECT * FROM data");
while($row = mysql_fetch_array($result)){
$data=$row['dataColumn'];
if (!in_array($data,$stringA)) echo $data . "<br>";
}//end while

If you have data that needs to be exploded in the column we can go deeper.

$myString="v1,v2,v3";
$stringA=explode(",",$myString);

$result=mysql_query("SELECT * FROM data");
while($row = mysql_fetch_array($result)){
$data=$row['dataColumn'];
$da=explode(",",$data);
foreach($da as $value) if (!in_array($value,$stringA)) echo $data . "<br>";
}//end while

Upvotes: 1

jogesh_pi
jogesh_pi

Reputation: 9782

the logic behind this is first explode the string with the explode(", ", $string) function.
So that it will become an array.

And on the other hand check the value with the function in_array(),

For example:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}
//output : 'ph' was found

Upvotes: 0

Related Questions