Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements of one array if it is found in another [duplicate]

Tags:

arrays

php

Possible Duplicate:
Remove item from array if it exists in a 'disallowed words' array

I have a dynamic string that clients will send and I want to create comma delimited tags from it:

$subject = "Warmly little in before cousin as sussex and an entire set Blessing it ladyship."; print_r($tags = explode(" ", strtolower($subject))); 

And yet, I want to delete a specific group of words (such as definite articles), but I want to delete the key and value of that word if it is in the exploded array:

$definite_articles = array('the','this','then','there','from','for','to','as','and','or','is','was','be','can','could','would','isn\'t','wasn\'t', 'until','should','give','has','have','are','some','it','in','if','so','of','on','at','an','who','what','when','where','why','we','been','maybe','further'); 

If one of these words in the $definite_article array are in the $tags array delete the key and value of that word and the new array will have these words taken out. I will have this array be used by array_rand to have a random group of words chosen out of it. I've tried many things to achieve my result, but nothing so far. Can someone help me find a resolve to this?

like image 215
Tower Avatar asked May 14 '12 19:05

Tower


People also ask

How do I remove from an array those elements that exists in another array?

To remove elements contained in another array, we can use a combination of the array filter() method and the Set() constructor function in JavaScript.

How do you remove duplicate values from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

How do you get the elements of one array which are not present in another array using JavaScript?

Use the . filter() method on the first array and check if the elements of first array are not present in the second array, Include those elements in the output.


2 Answers

You are looking for array_diff:

$subject = "Warmly little in before cousin as sussex..."; $tags = explode(" ", strtolower($subject));  $definite_articles = array('the','this','then','there','from','for','to','as');  $tags = array_diff($tags, $definite_articles); print_r($tags); 

See it in action.

like image 109
Jon Avatar answered Sep 21 '22 15:09

Jon


Sounds like an easy job for array_diff().

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against array2 and returns the difference.

Which basically means it will return array1 after it's been stripped of all values which exist in array2.

like image 43
Madara's Ghost Avatar answered Sep 20 '22 15:09

Madara's Ghost