Search code examples
phppreg-match

Matching both preg_matches in an if statement


I have 2 preg_match in an if statement, and if either of them are true, I want to print_r both of them. But for some reason, only the first preg_match is being matched each time, even though both of them has the same pattern. Why is this happening?

<?php

$string = "how much is it?";
if (preg_match("~\b(how (much|many))\b~", $string, $match1) || preg_match("~\b(how (much|many))\b~", $string, $match2)) {
print_r($match1);
print_r($match2);   
}

?>

Result:

Array ( [0] => how much [1] => how much [2] => much )

Expected Result:

Array ( [0] => how much [1] => how much [2] => much )
Array ( [0] => how much [1] => how much [2] => much )

Solution

  • Explanation:-

    Due to || condition when first one is correct at-once if is executed by ignoring second one. so first one outputs array, but second one gives an Notice: Undefined variable: match2 in D:\xampp\htdocs\abc.php on line 6. It's wierd that you didn't get that error.

    If you want both as output use && instead of || so that both will check and both will print

    So code will be:-

    <?php
    
    $string = "how much is it?";
    if (preg_match("~\b(how (much|many))\b~", $string, $match1) && preg_match("~\b(how (much|many))\b~", $string, $match2)) {
    print_r($match1);
    print_r($match2);   
    }
    
    ?>
    

    Output:-https://eval.in/595814

    Another solution:-

    <?php
        $string = "how much is it?";
        preg_match("~\b(how (much|many))\b~", $string, $match1);
        preg_match("~\b(how (much|many))\b~", $string, $match2);
        print_r($match1);
        print_r($match2);   
    ?>
    

    For more learning:- http://php.net/manual/en/language.operators.logical.php