0

This is a common simple question that bothers me. I have an array stored in a variable and I want to search and match the string array value($myarray) from a string that is stored in a variable($match). How can I match the values using loop and count it if how many matches are there? Should I use for loop or while loop or for each? This is my sample data.

$myArray = array('one', 'two', 'three', 'four', 'five');
$count = count($myArray);
$match = 'six';
$match2 = array('car', 'dog');

for ($myArray=0; $myArray < $count; $myArray++) { 
    if($myArray == $match){
        echo 'do something';
    }else{
        echo 'do something';
    }
}

Also is it possible to match the value of one array to another array? For example, I want to search all the values of $myArray and match it to the values of $match2 and return all matches(like: 2 matches out of 10 items)

I don't have enough knowledge in loops or handling arrays. Thank you for help.

2
  • I prefer to use foreach because it's simpler and more obvious what you're doing. But to each his own, you can use whatever you like. Commented Jan 31, 2015 at 17:27
  • Thanks for giving me additional idea. Now I have something in mind to follow. Can you give me a sample code using for each loop? Commented Jan 31, 2015 at 17:32

2 Answers 2

4

I think the function you're looking for is array_intersect(). You give this 2 arrays, and it returns an array containing the elements that they have in common. You can then use count() to get the number.

$matches = count(array_intersect($myArray, $match2));
Sign up to request clarification or add additional context in comments.

11 Comments

PHP has several handy built-in array functions: php.net/manual/en/ref.array.php
Wow! nice it counts all matches. how about if I want to echo all the matched values?
Put the result of array_intersect in a variable and loop over it.
I'm not good in looping but I will try it. Can you give me example?
There's nothing to it. foreach ($array as $element) {echo $element;}
|
0

You need a variable, not your array variable, to see the current index in your cycle, we'll name this one index, then you compare the string in that position with the string you want yo match.

$myArray = array('one', 'two', 'three', 'four', 'five');
$count = count($myArray);
$match = 'six';
$match2 = array('car', 'dog');
$numberMatches = 0;

for ($index=0; $index < $count; $index++) { 
    if($myArray[index] == $match){
        echo "It matches" ;
        $numberMatches++;
    }else{
        echo "It doesn' t match";
    }
}

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.