0

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

1
  • 4
    Why do you have data stored like this in the first place? It sounds like somewhere along the line, you or someone else broke the rules of normalization. Commented Sep 7, 2010 at 15:16

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks - do you mean I shouldnt use a comma to separate values? in other fields I have used a semicolon. Is this ok?
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 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!
0

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

Comments

0

try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.