0

Iv been looking for a way to search through an array of strings and find if there are any strings that contain a part of another string, if there is then i merge the whole array onto another array. EG:

Searching for jav:
array->[java] -> would return this value
and add that whole array to another

After looking around on stackoverflow and testing i found this solution using strpos which works...kind of:

$matches=array(); //just here to show the array is declared and is filled with items prior to calling 

foreach($myarray as $fn){
    if(strpos($fn,$searchString)){
        $matches = array_merge($myarray,$matches);
    }
    }

The issue is, instead of adding the whole array its adding my search string each loop however, after double checking a number of times i dont understand why. Tts adding the original search item rather than the entire other array.... EG.

If i search for jav as shown above the array will merge to create an array of the correct length but with the value :

javjavjavjavjav

Any help in understanding exactly why this is or how to correct it would be appreciated.

3
  • what does $myarray contain? example, is this just a simple flat array? Commented Aug 23, 2016 at 23:30
  • My array contains a list of words such as java,csharp,c++ etc so I expected the match of jav to java to results it in merging the array to the other array but instead it merges the search string the correct number of times.. Commented Aug 23, 2016 at 23:32
  • just merge $fn not $myarray, just like below Commented Aug 23, 2016 at 23:35

1 Answer 1

1

The function strpos return false or 0, so the array matches will not save any word with text jav.

This is my solution:

$myarray = ['java', 'java3', 'mouse', 'java2', 'keyboard'];
$matches = [];
foreach ($myarray as $fn) {
    if (strpos($fn, 'jav') !== false) {
        $matches[] = $fn;
    }
}

PS: I don't know if i understood correctly your question, but i hope.

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

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.