Home > Mobile >  Why is the elseif statement failing?
Why is the elseif statement failing?

Time:10-13

What am I missing here? It puts the APT in red but doesn't find the LOT occurrences. If I remove the elseif statement all together and change the APT to LOT it works fine for the LOT occurrences. Why won't it find both?

    if (strrchr($row["Address"], "APT") == true)    {
        $keyword = "APT";
        $addr = preg_replace('/\b' . preg_quote($keyword) . '\s*\w /i', ', <span style="color:red;">$0</span>', $row['Address']);
    }
    elseif (strrchr($row["Address"], "LOT") == true)    {
        $keyword = "LOT";
        $addr = preg_replace('/\b' . preg_quote($keyword) . '\s*\w /i', ', <span style="color:red;">$0</span>', $row['Address']);
    }   
    else {
    $addr = $row["Address"];
    }

CodePudding user response:

strrchr() is a character search, not a string search. You need to using something like strpos() instead.

For example:

if (strrchr('ABC','AB')){
  echo 'found';
}

And

if (strrchr('ABC','BA')){
  echo 'found';
}

Both display found as the first character in the needle (A in the first, and B in the second) are found.

If you want to find a string instead of a character match, you need to use something like strpos() instead.

if (strpos('ABC','AB') !== true){
  echo 'found';
}

And

if (strpos('ABC','BA') !== true){
  echo 'found';
}

Only the first example will display found. Note: You need to use !== false as strpos() will return either the string position or false.

CodePudding user response:

It looks like, since the patterns are the same, and the replacement is the same for both APT and LOT, you could just put them both into the same preg_replace call.

The if/elseif seems redundant to me anyway since the pattern won't match and nothing will be replaced if those keywords aren't in the string.

$addr = preg_replace('/\b(?:LOT|APT)\s*\w /i', ', <span style="color:red;">$0</span>', $row['Address']);
  • Related