0
$find=array('or','and','not');
$text=array('jasvjasvor','asmasnand','tekjbdkcjbdsnot');

I have to check if text array contains any of the elements find has. I'm able to do this for single text but don't know how to do it for all texts

$counter=0;  
foreach($find as $txt){
        if (strstr($text[0], $txt)) {
        $counter++;
}

If i use this technique i'll have to run foreach number of times. Is there any other way to do this?

NOTE if array value contains or,and ,not not the whole word match

http://codepad.viper-7.com/VKBMtP

Input

$find=array('or','and','not');
$text=array('jasvjasvor','asmasn','tekjbdkcjbdsnot'); 
// array values "jasvjasvor" and "tekjbdkcjbdsnot" contains words `or,not`

Output

2 -> as two words from find array are contained in text array values

0

2 Answers 2

4

Use array_intersect():

if (count(array_intersect($find, $text)) >= 1) {
    // both arrays have at least one common element
}

Demo.


UPDATE: If you're trying to find how many elements in $text array contain any of the values (partial match or whole-word match) in $find array, you can use the following solution:

$counter = 0;
foreach($find as $needle) {
    foreach ($text as $haystack) {
        if(strpos($haystack, $needle) !== false) $counter++;
    }
}
echo $counter; // => 2

Demo.

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

6 Comments

I want if array value contains or,and ,not not the whole word match
@Ace: I'm not sure what you're trying to achieve. Could you post the expected output in the question?
@AmalMurali in the question text array has jasvjasvor as value it contains word or somewhere in the string. I want to verify that if it contains the words that are in $find array
@AmalMurali tnx. foreach will run many number of times. Will it affect speed or functioning in any way?
@Ace: The inner foreach loop will execute 9 times, which is the number of array elements in $find multiplied by number of array elements in $text. If $text had 5 elements, then the inner foreach loop will execute 15 times.
|
0
$counter=0;  
foreach($find as $txt){
 foreach($txt as $value){
        if (strstr($value, $txt)) {
        $counter++;
}
}

1 Comment

The code should be like codepad.viper-7.com/6UcMol. your code is working ok. but if there are lot of symbols and lot of texts it will run foreach a number of time. Is there an easy way?

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.