Refactor nested foreach loop based on object property I'm using a levenshtein matching algorithm to match a title to a filename (for anime). I either use the main show title for matching or its alternative titles (flexget_titles).

For that I have the following snippet of code.

public function matchFilenameToShow($filename)
{
    $shows = $this-&gt;shows-&gt;getAll();
    $shortest = -1;
    $clean_name = $this-&gt;removeEpisodeNumber($this-&gt;cleanFilename($filename));
    foreach ($shows as $show) {
        if (!empty($show-&gt;flexget_titles_array)) {
            foreach ($show-&gt;flexget_titles_array as $title) {
                // calculate the distance between the input string filename,
                // and the current show name
                $lev = levenshtein(strtolower($clean_name), strtolower($title));
                // if this distance is less than the next found shortest
                // distance, OR if a next shortest distance to the word has not yet been found
                if ($lev &lt;= $shortest || $shortest &lt; 0) {
                    // set the closest match, and shortest distance
                    $matchedShow = $show;
                    $shortest = $lev;
                }
            }
        } else {
            // calculate the distance between the input string filename,
            // and the current show name
            $lev = levenshtein(strtolower($clean_name), strtolower($show-&gt;title));
            // if this distance is less than the next found shortest
            // distance, OR if a next shortest distance to the word has not yet been found
            if ($lev &lt;= $shortest || $shortest &lt; 0) {
                // set the closest match, and shortest distance
                $matchedShow = $show;
                $shortest = $lev;
            }
        }
    }
    return $matchedShow;
}


Obviously there is code repetition and I want to refactor this. However I'm not sure how to do it. I have a feeling that I need to extract that levenshtein part to a separate method, but I need to return 2 variables.
You can create "fallback" version of nested array in the case when $show-&gt;flexget_titles_array is empty and handle it with the same nested foreach loop:

...
foreach ($shows as $show) {
    ($arr = $show-&gt;flexget_titles_array) || ($arr = array($show-&gt;title));
    foreach ($arr as $title) {
        // calculate the distance between the input string filename,
        // and the current show name
        $lev = levenshtein(strtolower($clean_name), strtolower($title));
        // if this distance is less than the next found shortest
        // distance, OR if a next shortest distance to the word has not yet been found
        if ($lev &lt;= $shortest || $shortest &lt; 0) {
            // set the closest match, and shortest distance
            $matchedShow = $show;
            $shortest = $lev;
        }
    }
}
...