views:

66

answers:

3

I want to be able to easily and quickly delete an array of needles from a haystack array. In actual fact I have a comma separated list of numbers (though this is a string i know) that need to be deleted from a second comma separated list of number that I pull from a field in my sql database.

So I need -

$orig_needle_list = "3456,5678"; The haystack list is in a field in a mysql database and is "3456, 4567, 5678, 6789" - so I basically want to update this field to "4567,6789"

Q1. Should I retrieve the haystack list, convert both to arrays and iterate over them with a nested foreach cycle and array_splice any matched values?

Q2 Can I use in_array to be faster than nested foreach method?

Q3 is there a way to cut out the middle man and update the field by performing this in an sql query?

thanks

A: 

I think you are looking for array_intersect() http://php.net/manual/en/function.array-intersect.php

Yorirou
A: 

try this:

implode(",",array_diff(explode(",",$haystack),explode(",",$orig_needle_list)));

dweeves
+5  A: 

Hi,

you don't need to iterate over things, there's a function called array_diff:

http://www.php.net/manual/en/function.array-diff.php

So create 2 arrays of the comma separated list and use array_diff, the resulting array is the difference of these two.

Storing comma separated lists in a database isn't a good idea because it breaks normalization.

sled
thanks - do you mean I shouldnt use a comma to separate values? in other fields I have used a semicolon. Is this ok?
undefined
the problem is not that you use commas or semicolons, the problem is you're storing multiple values in one database field (column) ! It'd be better to create an extra table with a foreign key to it's parent table to store the value. Look at http://en.wikipedia.org/wiki/Database_normalization You'll have many new rows in this new table but that's not a problem for your SQL server, indeed it speeds things up because it can index it. You could also perform this operation (array_diff) directly in the DB!
sled