0

new with recursive thing and i want to create search engine depend on value user typing and get it from array values all word in value that user typing

for example i have this array :

$array = array('it', 'pro', 'gram', 'mer', 'programmer');
$string = "itprogrammer";

sorry bad grammar. if anyone can help i appreciate it a lot. thanks you for your help.

4
  • Why does it need to be recursive? Commented Oct 4, 2018 at 3:29
  • I don't see how it can be recursive. Usually recursive is when the array is multidimensional, this is a flat array. Commented Oct 4, 2018 at 3:33
  • @Andreas thanks for explanation. so is it any possible or it just impossible doing it in flat array? Commented Oct 4, 2018 at 3:36
  • 1
    As I said, I don't know how to do recursive on a flat array. Maybe it's possible. But I don't see why it should be recursive. Commented Oct 4, 2018 at 3:37

1 Answer 1

4

You can use array_filter to filter out any values of the array which are not a substring of $string. Note I have used stripos for a case-insensitive search, if you want the search to be case-sensitive just use strpos instead.

$array = array('pro', 'gram', 'merit', 'program', 'it', 'programmer'); 
$string = "programit";
print_r(array_filter($array, function ($v) use($string) { return stripos($string, $v) !== false; }));

Output:

array
(
    [0] => pro
    [1] => gram
    [3] => program
    [4] => it
)

Update

Here is a recursive function which gives the same result.

function find_words($string, $array) {
    if (count($array) == 0) return $array;
    if (stripos($string, $array[0]) !== false)
        return array_merge(array($array[0]), find_words($string, array_slice($array, 1)));
    else
        return find_words($string, array_slice($array, 1));
}

Demo of both methods on rextester

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

17 Comments

You missed " i hope is 'pro,gram,it' "
@IhsanDn this isn't really a problem that is well suited to recursion as you need to process the values in $array one by one.
@IhsanDn by the way I added a recursive function to my answer based on your original data.
@IhsanDn if you want to output the values separated by <br> you can just echo implode('<br>', find_words($string, $array));
@IhsanDn see my edit, i've included a link to a demo of both versions running on PHP7 on rextester.
|

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.