undefined
undefined

Reputation: 5328

What is the best way to delete an array of values from an array?

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

Upvotes: 0

Views: 145

Answers (3)

dweeves
dweeves

Reputation: 5605

try this:

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

Upvotes: 0

sled
sled

Reputation: 14635

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.

Upvotes: 5

tamasd
tamasd

Reputation: 5913

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

Upvotes: 0

Related Questions