Search code examples
phprecursion

Recursive search algorithm always returns false


I know how strpos() works, and it is working as expected, but the return in the if function isn't.

Some code:

foreach ($socialstream as $key => $social) {
    //filtering in here
    $result= $this->search_objects($social);
    ....
}

My function search_objects:

function search_objects($objects)
{
    $filters = array('word', 'test');
    foreach ($objects as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $this->search_objects($value);
        } else {
            //look for faulty strings in value
            foreach ($filters as $filter) {
                if (!is_int($value) && strpos($value, $filter) !== false) {
                    return true;
                }
            }

        }
    }
    return false;
}

If I print out my $result, I always get false back, instead of the true in the if function. I know it gets to the if when the needle exists in the haystack, by debugging, it's just not returning it.

What am I missing?


Solution

  • I think your problem has to do with the recursive part:

        if (is_array($value) || is_object($value)) {
            $this->search_objects($value);
        }
    

    You probably want to do something with the return value. Like: if ($this->search_objects($value)) return true;

    (Then again, I'm not sure what you are trying to accomplish)

    edit: Try this:

    function search_objects($objects)
    {
        $filters = array('word', 'test');
        foreach ($objects as $key => $value) {
            if (is_array($value) || is_object($value)) {
                if ($this->search_objects($value)) {
                    return true;
                }
            } else {
                //look for faulty strings in value
                foreach ($filters as $filter) {
                    if (!is_int($value) && strpos($value, $filter) !== false) {
                        return true;
                    }
                }
    
            }
        }
        return false;
    }