Home > Blockchain >  If-Else return hard-coded string if no match
If-Else return hard-coded string if no match

Time:08-30

I have a code which returns the id of the author whose name is contained more than once in the text of the article. It works just fine.

In addition to that, I would like the code to return a default id in case non of the authors meet the criteria.

<?php
$article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson.";

$authors = [1=>'Smith', 2=>'Jackson', 3=>'Peters'];

foreach ($authors as $id=>$author) {
    preg_match_all('/\b'.$author.'\b/', $article, $match);
    if (count($match[0])>1) {
        return $id; 
    }
}
?>

I tried with adding simple 'else' like below but it does not work.

<?php
$article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson.";

$authors = [1=>'Smith', 2=>'Phillips', 3=>'Peters'];

foreach ($authors as $id=>$author) {
    preg_match_all('/\b'.$author.'\b/', $article, $match);
    if (count($match[0])>1) {
        return $id;
    }
    else {
        return '1899';
    }
}
?>

Any suggestions how to achieve this result?

CodePudding user response:

<?php
$article = "This is a article is written by the three authors - Smith, Jackson, Peters. Peterson is not author. The main author of the article is Jackson.";

$authors = [1=>'Smith', 2=>'Jackson', 3=>'Peters'];

foreach ($authors as $id=>$author) {
    preg_match_all('/\b'.$author.'\b/', $article, $match);
    if (count($match[0])>1) {
        return $id; 
    }
}
return '1899';
?>
  • Related